Displaying file names from a directory

Hi,

I’m reasonably new to php, I’m trying to display a list of file names including the file type from a directory containing images. The problem I have is I don’t want to show the sub directories, or if possible set it to only show the image files only, my code is below and the specific questions underneath.

[php]
$dir = $_SERVER[‘DOCUMENT_ROOT’] . ‘/images/Gallery/’;
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if ($file != “.” && $file != “…” && $file !=filetype($file)) {
echo “
”;
}
}
}
closedir($handle);
[/php]

Questions:

What do I need to add with the exclude ‘.’ And ‘…’ To exclude folders in this directory, if possible?

Otherwise is there a way to only display all image files rather then having to specify all the ‘.png’ ‘.jpg’ etc?

Hi there, to be honest I would personally suggest a simpler and easier way of traversing the directory and removing unwanted items. See below:

[php]$dir = ‘./’;
$items = array_slice(scandir($dir),2); //scandir returns all items in $dir, array_slice returns items after the first 2 (’.’ and ‘…’)
foreach($items as $item)
{
if(is_file($dir.$item))
{
//use $item (file name only - no path)
}
}[/php]

I would recommend using the built in DirectoryIterator class.

http://php.net/manual/en/class.directoryiterator.php

Forget all that, just use glob(),
[php]foreach(glob($dir.’.’) as $file) {
echo “<img src=’/images/Gallery/$file style=‘width:5em;’>
”;
}[/php]

is it Gellery or Gallery? And the . assumes that all file inside $dir are already images. If you want to be more specific, you could create an array and use another foreach loop to get just the types you want.

That’s a typo it should gallery,

Thanks for the responses guys will be trying them out shortly!

Much appreciated!

I don’t believe the simplest solution is always the best :wink: Here is how I would do it:

[php]
foreach(new DirectoryIterator($_SERVER[‘DOCUMENT_ROOT’] . ‘/images/Gallery/’ as $file) {
if (!$file->isFile()) {
continue; // skip all directories
}

// validate extension of current file
$extension = pathinfo($file->getPathname(), PATHINFO_EXTENSION);
if (!in_array($extension, array('jpg', 'gif', 'png'))) {
	continue; // skip all files that are not jpg, gif, or png
}

// output valid image
echo "<img src='/images/Gellery/" . $file->getFilename() . "' style='width:5em;'><br />"

}
[/php]

Sponsor our Newsletter | Privacy Policy | Terms of Service