?
Solved

Random filename from directory?

Posted on 2004-04-15
6
Medium Priority
?
395 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 2000 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
WordPress Tutorial 3: Plugins, Themes, and Widgets

The three most common changes you will make to your website involve the look (themes), the functionality (plugins), and modular elements (widgets).

In this article we will briefly define each again, and give you directions on how to install them.

 
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

Want to be a Web Developer? Get Certified Today!

Enroll in the Certified Web Development Professional course package to learn HTML, Javascript, and PHP. Build a solid foundation to work toward your dream job!

Question has a verified solution.

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

Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to count occurrences of each item in an array.
Suggested Courses

762 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