Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

Random file selection

Posted on 2005-03-01
14
Medium Priority
?
258 Views
Last Modified: 2010-05-19
Hello all -
I have a directory containing say 100 images. They are labeled in no special way. When a page loads, I would like a random filename from this directory to be grabbed.

I found this code elsewhere in EE. I am unsure how to modify something like this to return one single filename, and RANDOMLY. Ideas? THANKS!!

<?php
$dir = "/tmp/";

// 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);
   }
}
?>
0
Comment
Question by:D4Ly
  • 6
  • 4
  • 4
14 Comments
 
LVL 20

Expert Comment

by:virmaior
ID: 13430678
<?php
$dir = "/tmp/";

// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
   if ($dh = opendir($dir)) {
       while (($file = readdir($dh)) !== false) {
        // put some sort of if to match to the filetype you want filetype($dir . $file)
           $files[] =   $file;
       }
       closedir($dh);
   }
}

echo $files[rand(1,count($files))];

?>

I would however advise against this route.  Instead, I'd recommend populating a DB with a list of the files in the directory and then selecting a random record from that.
0
 
LVL 9

Author Comment

by:D4Ly
ID: 13430722
The thing with that virmaior is that I want simplicity over all. Uploading a new image is all I want to do to update. I will be able to try your code out in a couple hours and then get right back to you. Thanks this far!!
0
 
LVL 9

Author Comment

by:D4Ly
ID: 13430726
And why exactly would you advise against this?
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 20

Expert Comment

by:virmaior
ID: 13430839
it's slow.  You have to do a new directory scan every time you run the page, and HDs are the slowest component in a computer system.  Even when they can read things really fast, it's asking a lot of them to do this every time.

there's nothing wrong with using this method to populate the DB, I'd just recommend making it some sort of a refresh element that won't get called every time the page is run.
0
 
LVL 11

Expert Comment

by:ZhaawZ
ID: 13431775
<?php
# function that will make a db file with filenames
function update_images_db() {
  $db_file = fopen('images_db.php', 'w');
  fwrite($db_file, "<?php\n");
  $dir = opendir('images');
  while ( ($file = readdir($dir)) !== false ) {
    if ( is_file('images/'.$file) ) {
      fwrite($db_file, "\$images[] = '{$file}';\n");
    }
  }
  closedir($dir);
  fwrite($db_file, "?>\n");
  fclose($db_file);
}

# call this *only* when you have uploaded or deleted some image from directory.
# it will make a 'images_db.php' file that will contain all filenames so you can use it
# later without reading all the directory
update_images_db();

# get a db (an array made by update_images_db() that containts filenames)
include('images_db.php');

# output a random filename from folder
echo 'images/'.$images[array_rand($images)];
?>
0
 
LVL 9

Author Comment

by:D4Ly
ID: 13433430
k, silly question:
Warning: opendir(imagetest): failed to open dir: No such file or directory in /home/d4lycoma/public_html/imagetest/update_db.php on line 6

i have the file IN imagetest that is trying to create the file in imagetest. I am referencing it this way:
$dir = opendir('imagetest');

whats the problem?
0
 
LVL 11

Expert Comment

by:ZhaawZ
ID: 13433478
try opendir('.');
0
 
LVL 9

Author Comment

by:D4Ly
ID: 13433586
ok. Now for the part where I simply learn something, as this works wonderfully...

the array file writes like this:

$images[] = '01.jpg';
$images[] = '02.jpg';
$images[] = '03.jpg';
$images[] = '04.jpg';

and so on. Why don't you need to reference indices?

$images[0] = '01.jpg';
$images[1] = '02.jpg';
$images[2] = '03.jpg';
$images[3] = '04.jpg';

Next, what does opendir('.'); do? Call the directory that this file is located in? What if now I want to move this file up one in the directory structure...how do I reference the imagetest directory then?

and finally, do you think this is a better approach doing this through a mysql table? instead of writing a file, would it be better to simply re-create the mysql table?
0
 
LVL 20

Expert Comment

by:virmaior
ID: 13433725
the indices are auto-incrementing.
$images[] will automatically put the next highest integer index.
(it can be slightly buggy if you do lots of tricky things in between uses).
the table and DB options each have performance advantages/disadvantages.
the longer the list, the better the advantage of using DB.
0
 
LVL 11

Accepted Solution

by:
ZhaawZ earned 1400 total points
ID: 13433726
1) Assigning a value to $images[] (with empty square brackets) will add a value to the end of array. If an array doesn't exist, it will be created.

2) opendir('.') will open current working directory handle, because '.' is current directory.
If I`m not mistaken, by default current directory is a directory where the root php file is.
'..' is a directory where the current directory is in.
A short example..
/dir0/dir1/dir2/index.php
/dir0/dir1/dir2/dir3/dir4/
If you need to open /dir0/dir1/dir2/dir3/dir4/ from index.php, use opendir('dir3/dir4')
If you need to open /dir0/dir1/dir2/dir3/ from index.php, use opendir('dir3')
If you need to open /dir0/dir1/dir2/ from index.php, use opendir('.')
If you need to open /dir0/dir1/ from index.php, use opendir('..')
If you need to open /dir0/ from index.php, use opendir('../..')

3) mm.. Actually I don`t know :) Is there any use of mysql table that has only one column?
0
 
LVL 20

Expert Comment

by:virmaior
ID: 13434308
you could start tracking how often each image showed up..
0
 
LVL 9

Author Comment

by:D4Ly
ID: 13434429
haha...thanks very much to both of you for the info, but to ZhaawZ for the answer!

VERY HELPFUL.

Here's what I'm doing:
I have the header to my personal website that I'm designing. I have a bunch of pictures that I have cropped and ps'ed, all with my site logo on it. I then have them all stored in a directory alone. Then, from the pages with the header, which will be made in flash, the call will be made to grab one of these random images to load and display. Then on a button click in the header, another request will be made for another random image to load. The actual image names won't matter because of this php script. I will just have to upload and run the updater. Perfect!
0
 
LVL 9

Author Comment

by:D4Ly
ID: 13434657
ooo, one last q.

function updateImagesDb(){
              $db_file = fopen('images_db.php', 'w');
              fwrite($db_file, "<?php\n");
              $dir = opendir('../images/headers/');
              while ( ($file = readdir($dir)) !== false ) {
                     if ( is_file('../images/headers/'.$file) ) {
                              fwrite($db_file, "\t\$images[] = '{$file}';\n");
                }
              }
             closedir($dir);
              fwrite($db_file, "?>\n");
              fclose($db_file);
      }

which '../images/headers/' line must I modify to make the file being written get written to a specified folder?
0
 
LVL 11

Expert Comment

by:ZhaawZ
ID: 13435300
both of them?
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article discusses four methods for overlaying images in a container on a web page
There are times when I have encountered the need to decompress a response from a PHP request. This is how it's done, but you must have control of the request and you can set the Accept-Encoding header.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
Suggested Courses

571 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question