Wednesday, October 12, 2011

PHP- List All Files In A Directory

It’s actually a very simple process in PHP and only requires a small amount of code. I’ve seen a lot of examples on other forums/websites that use a ridiculous amount of code to get the same result, and i’m not quite sure why.

Here’s how to list all files in a directory

//path to directory to scan
$directory = "../images/team/harry/";
 
//get all image files with a .jpg extension.
$images = glob($directory . "*.jpg");
 
//print each file name
foreach($images as $image)
{
   echo $image;
}

Notes

The .jpg extension can be changed to any extension. So if you want to pull out only .txt files, you just need to replace the .jpg with .txt. If you want to list ALL files, just remove the condition.

No comments:

Post a Comment