Solved

Random filename from directory?

Posted on 2004-04-15
6
393 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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

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
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…
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…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

696 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