๐Ÿ“‚ PHP File Handling
Estimated reading: 3 minutes 31 views

๐Ÿ“ƒ PHP Listing Files โ€“ Read and Display Directory Contents in PHP

Learn how to list files and folders in PHP using built-in functions like scandir() and DirectoryIterator() for directory exploration and content rendering.


๐Ÿงฒ Introduction โ€“ Why List Files in PHP?

Listing files is essential for features like image galleries, file managers, download pages, or admin panels. PHP provides simple yet powerful tools to retrieve and display contents of directories dynamically.

๐ŸŽฏ In this guide, youโ€™ll learn:

  • How to list files using scandir() and glob()
  • How to loop through directories using DirectoryIterator
  • How to filter files and exclude . and ..
  • Best practices for secure and readable listings

๐Ÿ“‚ 1. Using scandir() to List Directory Files

$files = scandir("uploads");

foreach ($files as $file) {
    echo $file . "<br>";
}

โžก๏ธ Returns an array of filenames and folders in the specified directory.
โžก๏ธ Includes . (current) and .. (parent), which are usually excluded manually.


๐Ÿงน Filter . and ..

foreach ($files as $file) {
    if ($file !== "." && $file !== "..") {
        echo $file . "<br>";
    }
}

โžก๏ธ Skips system entries for cleaner output.
โžก๏ธ Essential for listing only actual files and folders.


๐Ÿ” 2. Using glob() to Filter File Types

$images = glob("images/*.jpg");

foreach ($images as $img) {
    echo "<img src='$img' width='100'><br>";
}

โžก๏ธ glob() uses pattern matching to return specific files.
โžก๏ธ Great for filtering by extension or filename pattern.


๐Ÿ“ฆ 3. Using DirectoryIterator (OOP Approach)

$dir = new DirectoryIterator("documents");

foreach ($dir as $fileinfo) {
    if (!$fileinfo->isDot()) {
        echo $fileinfo->getFilename() . "<br>";
    }
}

โžก๏ธ An object-oriented way to explore file properties.
โžก๏ธ You can check size, type, path, and timestamps easily.


๐Ÿ”„ 4. Checking File Type in a Directory

foreach (scandir("uploads") as $entry) {
    if ($entry !== "." && $entry !== "..") {
        echo is_dir("uploads/$entry") ? "[DIR] $entry" : "[FILE] $entry";
        echo "<br>";
    }
}

โžก๏ธ Use is_dir() to differentiate files and folders.
โžก๏ธ Useful for UI generation or permission handling.


๐Ÿ›ก๏ธ 5. Security Tips for Directory Listing

  • โœ… Always sanitize user input if using dynamic directories
  • โœ… Hide sensitive files (e.g., .env, .htaccess)
  • โœ… Disable auto-directory listing via Apache/NGINX if unwanted
  • โœ… Use realpath() or basename() to resolve safe paths
  • โŒ Never list directories based on unsanitized $_GET parameters

๐Ÿง  Best Practices

  • โœ… Use scandir() for simple listings
  • โœ… Use glob() for filtered results like *.pdf or *.txt
  • โœ… Use DirectoryIterator when metadata or file checks are needed
  • โœ… Always check file existence and handle . and .. explicitly
  • โœ… Consider pagination if the folder contains many files

๐Ÿ“Œ Summary โ€“ Recap & Next Steps

PHP provides multiple ways to list and manage file directories, allowing you to build robust content explorers, file upload viewers, or custom admin tools.

๐Ÿ” Key Takeaways:

  • Use scandir() or DirectoryIterator() for directory traversal
  • Use glob() to filter by extension or file type
  • Sanitize input and avoid exposing sensitive files
  • Combine file checks with file display for advanced features

โš™๏ธ Real-World Use Cases:
Media libraries, file managers, user uploads, download dashboards, CMS backend listings.


โ“ Frequently Asked Questions (FAQs)

โ“ How can I list only .txt files?
โœ… Use glob("path/*.txt").

โ“ Can I exclude subfolders in listing?
โœ… Yes. Use is_file() or filter out is_dir() entries.

โ“ Whatโ€™s better for performance: scandir() or DirectoryIterator()?
๐Ÿ”ธ scandir() is faster for simple tasks; DirectoryIterator() is better for complex filtering.

โ“ How do I sort the file list alphabetically?
โœ… Use sort() or natsort() on the scandir() array.

โ“ Can I use these functions on remote URLs?
โŒ No. These only work with local filesystem paths.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

๐Ÿ“ƒ PHP Listing Files

Or Copy Link

CONTENTS
Scroll to Top