Jump to content

Random Directory Problem


atlanta

Recommended Posts

Hi the code below wont output a random directory from the array can you check the code to see if anything is wrong thanks.

 

<?php
$cat = "/home/elvisand/public_html/photoalbum/";
function getRandomImage($path, $img, $realpath) {
    if ( $list = getImagesList($path) ) {
        mt_srand( (double)microtime() * 1000000 );
        $num = array_rand($list);
        $img = $list[$num];
    } 
    return $realpath . $img;
}

function getImagesList($path) {
    $ctr = 0;
    if ( $img_dir = @opendir($path) ) {
        while ( false !== ($img_file = readdir($img_dir)) ) {
            // can add checks for other image file types here
            if ( preg_match("/(\.gif|\.jpg)$/", $img_file) ) {
                $images[$ctr] = $img_file;
                $ctr++;
            }
        }
        closedir($img_dir);
        return $images;
    } 
    return false;
}

$hook = opendir($cat) or die('cant open dir');

$directories = array();

while (false!==($file = readdir($hook))) {
   
    $fpath = $cat . $file;
    
    if(is_dir($fpath))
    {
        if($file != '.' && $file != '..')
        {
        array_push($directories, $file);
        }
    }
}
closedir($hook);
$random = array_rand($directories, 1);
echo $directories[$random[0]];
$cat2 = "/home/elvisand/public_html/photoalbum/".$directories[$random[0]]."/";
$path2 = "http://www.elvisand.com/photoalbum/".$directories[$random[0]]."/";
$default = "";
?>
<img src="<? echo getRandomImage($cat2, $default, $path2); ?>" width="158" height="168"  />

Link to comment
https://forums.phpfreaks.com/topic/90006-random-directory-problem/
Share on other sites

Found the problem

 

 

$cat2 = "/home/elvisand/public_html/photoalbum/".$directories[$random[0]]."/";
$path2 = "http://www.elvisand.com/photoalbum/".$directories[$random[0]]."/";

 

should have been

 

$cat2 = "/home/elvisand/public_html/photoalbum/".$directories[$random[]]."/";
$path2 = "http://www.elvisand.com/photoalbum/".$directories[$random[]]."/";

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.