i have been busting my head trying to figure this out.
I found this snippet of code that works well , taken from the official php website. But if i place one image and one pdf in the folder it dosent show up. The photo.
I need a very simple way to scan a directroy, check if its jpg and then display just one photo.
Please tell me how i can change the following code or if i need to write something different for my needs.
<?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];?>" />
Thanks in advance again 🙂
john
Change the line
to
Do you use rand to pick a random image but you have to limit the values in the interval
[0, count($photos)-1] otherwise an index overflow can occurs. The bug afflicts your code but it is the case of a directory containings just an image that the problem is quite evident.
count($photo)equals to 1 and the array contains just an element with index 0.$rand=rand(0, count($photos)) => $rand=rand(0,1) => $rand can assume two different values: 0 or 1. In the first case all work as intended. In the latter the bug will spring out.
References:
http://www.php.net/rand
Addendum
In response to the comment: The code is quite efficient in case of an empty directory as the execution will skip the external for statement. You can use an if to skip all the code but the efficiency gain will be negligible.
I would use a different approach though, something like this: