Link to home
Start Free TrialLog in
Avatar of SandyCooke
SandyCooke

asked on

Random filename from directory?

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?
Avatar of madwax
madwax

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;
?>
ASKER CERTIFIED SOLUTION
Avatar of madwax
madwax

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of SandyCooke

ASKER

<?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 :)
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!


When you create a large array, does it use lots of resources?
The script will only be called by a Flash swf once per visit - surely that's ok?