📂 PHP File Handling
Estimated reading: 3 minutes 116 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 :
Share

📃 PHP Listing Files

Or Copy Link

CONTENTS
Scroll to Top