I'm attempting to list only jpg files in a directory. There's over 200, but using the code below, only about 100 get listed. I've tried different variations for extracting the file extension, but this has been the only one that's worked: $sub = substr($file, -3);
Can anyone tell me why all of the files are not showing up?
Complete source:
<?php
require('index.inc');
$page = new buildpage();
$page->buildHeader();
$currentdir = '/home/tim/Documents/Web/';
$dir = opendir($currentdir);
echo "<ol>";
while ($file = readdir($dir)){
$file = readdir($dir);
$sub = substr($file, -3);
$ext = "jpg";
if (strcasecmp($sub, $ext) == 0) {
echo "<li>$file</li>";
}
}
echo "</ol>";
?>
You have
$file = readdir($dir)
twice in there. So its read twice everytime.Thus 200 becoming 100. Take out the second one and it should work.
To extract the file extension, I would use
$ext = pathinfo($file, PATHINFO_EXTENSION);
As to why only some files show up, this could be related to jpeg files having the extension in differnt case, such das Jpg or JPG, or perhaps even "jpeg", which is also valid.
Edit: And of course, you have two readdir statements in there, as Iznogood pointed out.