Jump to content

Archived

This topic is now archived and is closed to further replies.

DaveLinger

find all files in a folder, choose one randomly

Recommended Posts

I'm working on a random background image selector... I'd like it to check the appropriate folder for all files (there would only be jpegs) and choose one filename and make it a variable. How is this accomplished?

Share this post


Link to post
Share on other sites
create a list of files, then count the lines, then feed that into a random number gen then display the line that equals the results

Share this post


Link to post
Share on other sites
well I mean I know how to randomly select from an array, just not how to find all files in a folder and put them into said array.

Share this post


Link to post
Share on other sites
okay, it says that

[code]<?php
$dir = "/images/";

// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
  if ($dh = opendir($dir)) {
      while (($file = readdir($dh)) !== false) {
          echo "filename: $file : filetype: " . filetype($dir . $file) . "\n";
      }
      closedir($dh);
  }
}
?> [/code]

should display any files in the "images" directory, but echos nothing. script is located...

domain
    www
          index.php
          test.php
          script.php
          images/
                image.jpg
                image2.jpg
                image3.jpg

Share this post


Link to post
Share on other sites
You may also want to look at the glob() function (http://www.php.net/glob) which returns all the file names in directory as an array. Then use array_rand() to select one at random.

[code]<?php
$dir = glob("images/*.jpg");
$rand_file = $dir[array_rand($dir)];
echo $rand_file;
?>[/code]

Ken

Share this post


Link to post
Share on other sites
You should look into [url=http://www.php.net/manual/en/function.scandir.php]scandir()[/url] too :)

Orio.

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.