Using the following code, I am able to display up to 10 images. What I want is to be able to display all images in the folder without going through an infinite loop and without testing if the image file exist at each loop.
for($i=1; $i<=10; $i++)
{
$filename = "/folder/$i.jpg";
echo "
<img title='$i' src='$filename'>
";
}
Assuming that I have no idea how many images there are in the folder and that I do not want to store this information in a database, how would you display all the images with file names are that are integers ending with a .jpg
extension?
//path to directory to scan
$directory = "/folder/";
//get all image files with a .jpg extension.
$images = glob($directory . "*.jpg");
UPDATE reference: http://php.net/manual/en/function.glob.php
I would use RecursiveDirectoryIterator http://au.php.net/manual/en/class.recursivedirectoryiterator.php if use use glob you will have to handle recursion manually.
$path = '/path/to/folder';
/* @var $file SplFileInfo */
foreach (new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path)) as $file) {
if ($file->isFile()
&& in_array(strtolower($file->getExtension()), array('jpg', 'png', 'gif'))) {
echo $file->getPathname()."
";
}
}
Please note that: SplFileInfo::getExtension is available from PHP 5.3.6