Solved

Random filename from directory?

Posted on 2004-04-15
6
388 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
  • 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
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 
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

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Both Easy and Powerful How easy is PHP? http://lmgtfy.com?q=how+easy+is+php (http://lmgtfy.com?q=how+easy+is+php)  Very easy.  It has been described as "a programming language even my grandmother can use." How powerful is PHP?  http://en.wikiped…
I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
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 a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

746 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

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now