Print all files from and below a directory with PHP

I had a gentleman ask me on a forum recently how to produce a simple list of all files within and below a particular directory.

Here’s some simple PHP code that will simply produce a list of all files below a particular directory and provide a link to that particular file. This code will just output files as raw unformatted data (or an array). I have a script that is formatted that I’ll provide in a few days.

<?php
function listdir($start_dir='.') {

// What is the name of this file?
$filename = "dirs.php";

  $files = array();
  if (is_dir($start_dir)) {
    $fh = opendir($start_dir);
    while (($file = readdir($fh)) !== false) {
      # loop through files, skipping . and .. recursing if necessary
      if (strcmp($file, '.')==0 || strcmp($file, '..')==0) continue;

	if ($file != "Thumb.db" && $file != "Thumbs.db" && $file != "$filename") {

      		$filepath = $start_dir . '/' . $file;
      		if ( is_dir($filepath) )
        	$files = array_merge($files, listdir($filepath));
      		else
        	array_push($files, $filepath);
	}
    }
    closedir($fh);
  } else {
    // false if function called with invalid non-directory argument
    $files = false;
  }
  return $files;
}

$files = listdir('.');

foreach($files as $myimages) {
echo "$myimages";
}
?>

If you want to output the data in an array simple comment out the last three lines of code (with a //) and replace with print_r($files);

Using GLOB

You can also use PHP’s GLOB function to return patterns from within a directory.

<?php
// Path of directory to search
$directory = "images/marty/";

// Get images with a .jpg extension.
$images = glob("" . $directory . "*.jpg");

// Print each file name
foreach($images as $image)
{
echo "$image";
}
?>

If you wanted to get images (or any files for that matter) with certain extensions you could use the following code (GLOB_BRACE – Expands {a,b,c} to match ‘a’, ‘b’, or ‘c’):

$images = glob(“” . $directory . “{*.jpg,*.gif,*.png}”, GLOB_BRACE);

And if you wanted to return everything in a directory, you could use the following:

$images = glob(“” . $directory . “*.*”);

If you liked this article, you may also like:

  1. Copy the contents of a directory from one location to another with PHP
  2. Zip a file or files with PHP
  3. Get current working directory (full path) to folder/file
  4. Working with CSV text files & PHP
  5. [Shortcode] Easily post an aviation Metar report into your post or page with shortcode
About Marty

is a passionate web developer from Sydney, Australia. He owns about 400 websites and makes a healthy living from working the web. As a day job, he works as a pilot for an international airline. You can follow Marty on Twitter or Google+.

Speak Your Mind

*