Jump to content

list all files in a directory


bill-lancaster
Go to solution Solved by bill-lancaster,

Recommended Posts

I'm new to this forum and also new to php coding.

I wish to list all the files in a given directory on my website and have seen quite a few examples but cant get any to work for me.

My code is located in /Gallery and I wish to list all files in /Gallery/Thumbnails.

What is the best way to go about this?

 

Link to comment
Share on other sites

Easiest way is using glob

 

Example

foreach(glob('Gallery/thumbnails/*') as $file)
{
    echo $file;
}

If you want to filter the images, by file extension use this instead   glob('Gallery/thumbnails/*.{gif,jpg,png,bmp}', GLOB_BRACE)

Edited by Ch0cu3r
Link to comment
Share on other sites

Try this simple example,

<?php
$dir = dirname(__FILE__)."/"; //Get the directory where this script is located

echo "This is the full path: ".$dir
echo "<br />\n";

// Open a known directory, and proceed to read its contents
if (is_dir($dir)) { //Checks its a directory
    if ($dh = opendir($dir)) { //Access the directory
        while (($file = readdir($dh)) !== false) { //read files/folder from the directory
            echo "filename: $file : filetype: " . filetype($dir . $file) . "\n"; //display the found item directory
        }
        closedir($dh);
    }
}
?>

it should give you the full of where the script is and what files and folders are inside.

 

The most common problem is getting the path right.

 

You could change dir in the above script  to

$dir = dirname(__FILE__)."/Thumbnails/"; //Get the directory where this script is located

If the script is in the Gallery directory..

 

Hope this helps

if not then just lets us know what happened :)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.