Wednesday, 3 January 2018

How to Get All File Names for a Directory with PHP

I fought with this for a while. I had to use PHP to return all file names in a directory with their respective size and types. I also had to return only files and not directories, but this guide will show you how to do both just in case you might need directories too.

Here is what the following code will return for a directory with three files in it:

Now here's the code that finally worked for me when I put the code in a file named get_file_names.php in the html directory which also held the "uploads" directory which it reads from :
//get the lastest file uploaded in uploads/
$path = "uploads";    
$d = dir($path);
while (false !== ($entry = $d->read())) {
$filepath = "{$path}/{$entry}";
//Check whether the entry is a file etc.:
    if(is_file($filepath)) {
    $latest_filename = $entry;
    $file_type = filetype($filepath);//get file type.
    $file_size = filesize($filepath);//get file size.
    echo "$latest_filename<br />Type: $file_type<br />Size: $file_size<hr />";
    }//end if is file etc.
}//end while going over files in uploads dir.
Wrap that in PHP tags and you got your get_file_names.php script.


0 comments:

Post a Comment