Php read directory file

I have a script that goes through a directory containing 3 images

$imglist=''; $img_folder = "path to my image"; //use the directory class $imgs = dir($img_folder); //read all files from the directory, checks if are images and ads them to a list while ($file = $imgs->read()) { if (eregi("gif", $file) || eregi("jpg", $file) || eregi("png", $file)) $imglist .= "$file "; } closedir($imgs->handle); //put all images into an array $imglist = explode(" ", $imglist); //display image foreach($imglist as $image) { echo '<img src="'.$img_folder.$image.'">'; } 

but the problem i am facing is displaying 4th img without image. but I have only 3 images in this folder.

+4
source share
4 answers

There is no need to create a row of images and then insert this row into an array of images, but simply add images directly to the array, as Radu mentioned. Here is the corrected code:

 $imglist = array(); $img_folder = "path to my image"; //use the directory class $imgs = dir($img_folder); //read all files from the directory, checks if are images and adds them to a list while ($file = $imgs->read()) { if (eregi("gif", $file) || eregi("jpg", $file) || eregi("png", $file)){ $imglist[] = $file; } } closedir($imgs->handle); //display image foreach($imglist as $image) { echo '<img src="'.$img_folder.$image.'">'; } 
+6
source

You will have a space at the end of the $imglist , which explode() will turn into an empty element. Trim the line:

 $imglist = explode(" ", trim($imglist)); 

Or even better, just add them to the $imglist array first, instead of creating a line and blowing it up:

 $imglist = array(); /* ... */ $imglist[] = $file; 
+2
source

ereg () is deprecated. You will probably be better off:

 chdir($img_folder); $imgs = glob('*.jpg *.gif *.png'); foreach ($imgs as $img) { echo "<img src=\"{$img_folder}/{$img}\">"; } 

glob () matches wildcards in the same way as most Unix shells.

+2
source
 Use [glob()][1] function <?php define('IMAGEPATH', 'path to my image/'.$imglist.'/'); foreach(glob(IMAGEPATH.'*.jpg') as $filename){ echo '<img src="'.$filename.'" alt="'.$album.'" />'; ?> [1]: http://www.php.net/manual/en/function.glob.php 
0
source

All Articles