Solved

Random filename from directory?

Posted on 2004-04-15
6
392 Views
Last Modified: 2008-02-26
This successfully returns the name of every file in a directory minus '.' and '..':

<?php
$dir = './images';
if ($handle = opendir($dir)) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            echo "$file\n";
        }
    }
    closedir($handle);
}
?>

Instead I want to return the url of just one random file, and I'm guessing the best way to do this is to add all the file names to an array and then pick a random index?

Is this the best way?

How would I code it?
0
Comment
Question by:SandyCooke
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
6 Comments
 
LVL 7

Expert Comment

by:madwax
ID: 10836311
I use the following function to get all files in a directory and i returns an array from which you can randomize a field:

<?
function recursive_listdir($base) {
   static $filelist = array();
   static $dirlist = array();

       if(is_dir($base)) {
       $dh = opendir($base);

       while (false !== ($dir = readdir($dh))) {
           if (is_dir($base ."/". $dir) && $dir !== '.' && $dir !== '..') {
               $subbase = $base ."/". $dir;
               $dirlist[] = $subbase;
               $subdirlist = recursive_listdir($subbase);
           } elseif(is_file($base ."/". $dir) && $dir !== '.' && $dir !== '..') {
               $filelist[] = $base ."/". $dir;
           }
       }
       closedir($dh);
   }
   $array['dirs'] = $dirlist;
   $array['files'] = $filelist;
   return $array;
}

/*get random file from the directorylisting*/
$dirAndFiles = recursive_listdir("d:/www_root/movies");
$randomFile = $dirAndFiles['files'][rand(1,count($dirAndFiles['files']))];
echo $randomFile;
?>
0
 
LVL 7

Accepted Solution

by:
madwax earned 500 total points
ID: 10836363
two things, change the rand(1,...) to rand(0,...) otherwise it will skip the first file in each directory. And the second thing do you run on a windows or linux server? you might have to change the slashes in the recursive function in order to it to work on a *nix machine.

Otherwise the random algorithm from an array is:

echo $myArray[rand(0,count($myArray))];

Regards,
//jan
0
 
LVL 2

Author Comment

by:SandyCooke
ID: 10836612
<?php

$dir = '.';

$myArray = array();

if ($handle = opendir($dir)) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            $myArray[] = $file;
        }
    }
    closedir($handle);
}

$totalFiles = count($myArray)-1;
$randomFile = $myArray[rand(0,$totalFiles)];

echo 'randomFile=' . $randomFile;

?>

Thanks :)
0
Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

 
LVL 2

Expert Comment

by:Fataqui
ID: 10836769
Hi


Doing this is not very wise! If you have a large directory it will create a large resource useage which you should never do!

Advice....

If the directories content's does not change or it does change daily or weekly, then you are better to create a cron job that reads the directory or after new images are added run a cache script that will build an include file that you can call from your random image script or function!

example............

cache image directory listing in a array, then include the cache file in your program.........

// example usage

include_once ( 'images.php' ); // returns the cached array called $images

<?

// unix path to img directory

$dir = "./httpdocs/services/img/";


// windows path to img directory

//$dir = "e:/www/docs/img/";

// include file path unix

$include = './httpdocs/service/images.php';

// include file path windows

//$include = 'e:/www/docs/zip/images.php';

// OS end of line character win = \r\n, linux = \n, mac = \r

$eol = "\n";


function this_ext ( $file )
{
      return substr ( $file, strrpos ( $file, "." ) + 1 );
}


function make_include ( $dir )
{

      $ok = array ( 'gif', 'jpg', 'jpeg', 'bmp', 'png', 'tif' );

      if ( $dh = opendir ( $dir ) )
      {

            while ( false !== ( $file = readdir ( $dh ) ) )
            {

                  if ( $file != "." && $file != ".." )
                  {

                        if ( is_file ( $dir . $file ) && in_array ( this_ext ( $file ), $ok ) )
                        {

                              $filelist[] = $file;

                        }
                        }
              }
           }

      closedir ( $dh );


       return implode ( "', '", $filelist );

}

$out  = '<?' . $eol;
$out .= '$image = array ( \'' . make_include($dir) . '\' );' . $eol;
$out .= '?>' . $eol;

$fp = fopen ( $include, 'w' );
fputs ( $fp, $out );
fclose ( $fp );



?>


Fataqui!


0
 
LVL 2

Author Comment

by:SandyCooke
ID: 10837189
When you create a large array, does it use lots of resources?
0
 
LVL 2

Author Comment

by:SandyCooke
ID: 10838255
The script will only be called by a Flash swf once per visit - surely that's ok?
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

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

Introduction This article is intended for those who are new to PHP error handling (https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html).  It addresses one of the most common problems that plague beginning PHP develop…
Many old projects have bad code, but the budget doesn't exist to rewrite the codebase. You can update this code to be safer by introducing contemporary input validation, sanitation, and safer database queries.
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…

733 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