开发者

Php read directory file

I have a script that goes through a directory that has 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) || e开发者_开发百科regi("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 that I am having is it display a 4th img with no image.. yet I only have 3 image in that folder.


There is no need to build a string of images and then explode that string into an array of images instead just add the images directly to an 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.'">';
}


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

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

Or better yet, just add them to the $imglist array in the first place, instead of making a string and exploding it:

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


ereg() is deprecated. You'd probably be better off with:

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

glob() does wildcard matching pretty much the same way as most Unix shells do.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜