php scandir jpg照片限制1


php scandir for jpg photos limit 1

我一直在绞尽脑汁想弄清楚这一点。

我发现这段代码运行良好,取自php官方网站。但是如果我把一张图片和一个pdf放在文件夹里,它就不会出现。照片。

我需要一个非常简单的方法来扫描directroy,检查它是否为jpg,然后只显示一张照片。

请告诉我如何更改以下代码,或者是否需要根据我的需要编写不同的代码。

<?php // no access
.............
// globals 
.............
// make article title lower case
$str = strtolower($articleTitle); 
$files= scandir("images/gallery/".$str."/");
$photos = array();
        for ($x=0; $x<count($files); $x++){
        $files[$x]="images/gallery/".$str."/".$files[$x];
                if (is_dir($files[$x])){
                $thisfolder=scandir($files[$x]);
                for ($f=0; $f<count($thisfolder); $f++)
                if (strpos(strtolower($thisfolder[$f]), ".jpg"))
                $photos[]=$files[$x]."/".$thisfolder[$f];
                }
        }
$rand=rand(0, count($photos)); ?>
<img src="includes/crop.php?src=<?php echo $photos[$rand];?>&h=115&w=650&q=90" title="<?php echo $photos[$rand];?>" />

再次提前感谢:)john

更改行

$rand=rand(0, count($photos))

$rand=rand(0, count($photos)-1)

你是否使用rand来挑选一个随机图像,但你必须限制间隔中的值[0,count($photos)-1]否则可能发生索引溢出。这个错误困扰着你的代码,但如果目录只包含一个映像,那么问题就很明显了。

count($photo)等于1,并且数组仅包含索引为0的元素。

$rand=rand(0,count($photos))=>$rand=rand(0,1)=>$rand可以采用两个不同的值:0或1。在第一种情况下,所有工作都按预期进行。在后者中,错误会突然出现。

参考文献:http://www.php.net/rand

附录

响应注释:在空目录的情况下,代码非常有效,因为执行将跳过外部for语句。您可以使用if跳过所有代码,但效率增益可以忽略不计。

.............
$str = strtolower($articleTitle); 
$files= scandir("images/gallery/".$str."/");
if (count($files)) {
    $photos = array();
        for ($x=0; $x<count($files); $x++){
        $files[$x]="images/gallery/".$str."/".$files[$x];
            if (is_dir($files[$x])){
                $thisfolder=scandir($files[$x]);
                for ($f=0; $f<count($thisfolder); $f++)
                if (strpos(strtolower($thisfolder[$f]), ".jpg"))
                    $photos[]=$files[$x]."/".$thisfolder[$f];
            }
        }
    $rand=rand(0, count($photos)-1);
    echo '<img src="includes/crop.php?src=' . $photos[$rand] 
       . '&h=115&w=650&q=90" title="'$photos[$rand]" />';
}

不过,我会使用一种不同的方法,比如这样:

$dirName = strtolower($articleTitle);
$oldDir = cwd();
chdir('images/gallery/'.$dirName);
$photos = glob('*.jpg');
$foreach(glob('*',GLOB_ONLYDIR) as $subdir) {
    $photos = array_merge($photos, glob($subdir.'/*.jpg'));
}
if (count($photos)) {
    $rand=rand(0, count($photos)-1);
    echo '<img src="includes/crop.php?src=' . $photos[$rand] 
         . '&h=115&w=650&q=90" title="'$photos[$rand]" />';
}
chdir($oldDir);

您可以尝试使用简单的代码

$files= scandir("images/"); $photos = ""; for ($x=0; $x < count($files); $x++){< if (strpos(strtolower($files[$x]), ".jpg")){ $photos = "images/".$files[$x]; break; } } ?> <img src="<?php echo $photos;?>" title="<?php echo $photos;?>" />