Forum Moderators: coopster

Message Too Old, No Replies

PHP loop filenames for gallery

How do I write PHP code to loop through varrying files in a folder

         

OSUsammy13

5:29 pm on Apr 19, 2004 (gmt 0)

10+ Year Member


How do I write PHP code to loop through varrying filenames in a folder? I have a script for making thumbnails out of images on the fly with PHP and GD.

the script works as if the page is an image such as <img src="/images/thumbnail.php?Image003.jpg">
I would like to loop through all of the files in a directory using a loop and a single command like <img src="/images/thumbnail.php?<?php echo $filename?>"> where $filename picks the next file in the folder.

I know that PHP is able to read directories and I would be able to do this if the filenames were in a database. Is anyone able to connect the dots for me and let me know how to get this done. thanks.

jatar_k

6:08 pm on Apr 19, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Welcome to WebmasterWorld OSUsammy13,

<? 
$mydir = "/path/to/dir/";
$d = dir($mydir);
while($entry = $d->read()) {
if ($entry!= "." && $entry!= "..") {
echo "<br><img src=\"/images/thumbnail.php?",$entry,"\">";
}
}
$d->close();
?>

I didn't test this but it should work. You just set the $mydir var and it should spit all your thumbnails out to the screen. I use this little filename reader a lot, it comes in quite handy. ;)

[edited by: jatar_k at 7:03 pm (utc) on April 19, 2004]

OSUsammy13

6:53 pm on Apr 19, 2004 (gmt 0)

10+ Year Member


where in the php is the variable $filename assigned to the file in that loop?

what is the additional "/" at the end of the echo?

Thank you for the quick reply - I have learned a lot just reading and searching the forums.

jatar_k

7:02 pm on Apr 19, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



oops, I edited the code and changed $filename to $entry. I also forgot to close the echo line.

I'm a big help today ;)

coopster

7:40 pm on Apr 19, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



glob [php.net] (PHP 4 >= 4.3.0) can be used to build an array of directory contents, too. At first I thought this was pretty cool...
$glob = glob("/path/to/dir/{*.gif,*.jpg}", GLOB_BRACE); 
natcasesort($glob);
foreach ($glob as $filename) {
echo "<br><img src=\"/images/thumbnail.php?",$filename,"\">";
}
...however, after some extensive testing, I've learned a few things about our friend, glob.
  1. jatar_k's dir method is consistently 3 times faster.
  2. glob is picky; any search patterns must be separated by commas with no spaces in between.
  3. glob is picky; pattern matching is case-sensitive.
    {*.GIF,*.Gif,*.giF}
    will not match any files with a
    .gif
    extension!
  4. glob won't sort as you expect; you still have to run a natural case sort
  5. dir is consistently 3 times faster than glob; yeah, I know I already said this, but figured it needed some emphasis

I just thought I'd share a bit this afternoon :)