Pull all images from a specified directory and then display them
You can display all image from a folder using simple php script. Suppose folder name “images” and put some image in this folder and then use any text editor and paste this code and run this script. This is php code
<?php
$files = glob("images/*.*");
for ($i=0; $i<count($files); $i++)
{
$image = $files[$i];
$supported_file = array(
'gif',
'jpg',
'jpeg',
'png'
);
$ext = strtolower(pathinfo($image, PATHINFO_EXTENSION));
if (in_array($ext, $supported_file)) {
echo basename($image)."<br />"; // show only image name if you want to show full path then use this code // echo $image."<br />";
echo '<img src="'.$image .'" alt="Random image" />'."<br /><br />";
} else {
continue;
}
}
?>
if you do not check image type then use this code
<?php
$files = glob("images/*.*");
for ($i = 0; $i < count($files); $i++) {
$image = $files[$i];
echo basename($image) . "<br />"; // show only image name if you want to show full path then use this code // echo $image."<br />";
echo '<img src="' . $image . '" alt="Random image" />' . "<br /><br />";
}
?>
You need to change the loop from for ($i=1; $i<count($files); $i++)
to for ($i=0; $i<count($files); $i++)
:
So the correct code is
<?php
$files = glob("images/*.*");
for ($i=0; $i<count($files); $i++) {
$image = $files[$i];
print $image ."<br />";
echo '<img src="'.$image .'" alt="Random image" />'."<br /><br />";
}
?>
You can also use glob
for this:
$dirname = "media/images/iconized/";
$images = glob($dirname."*.png");
foreach($images as $image) {
echo '<img src="'.$image.'" /><br />';
}