Free Web Hosting Provider - Web Hosting - E-commerce - High Speed Internet - Free Web Page
Search the Web

 
Random image (Randomly get from a directory)

Ever wanted to know how to create the random gallery ? Well, here is the way you can do it:

Script Name : Random image (expect a another version soon) Version :
Developer : Safras Ahamed Date 03/13/2003
Used Functions : opendir(), readdir(), closedir(), mt_srand(), microtime(), mt_rand()
 

<?
$imgpath
= "path/to/image/dir";
$handle = opendir( "$imgpath" );
$imgArray = array();
    while(
$file = readdir($handle)){
        if(
$file != "." && $file != ".." ){
            
array_push( $imgArray, $file );
        }
    }
    
    
closedir( $handle );
//huh if you open you have to close
    
mt_srand( (double)microtime( ) * 1000000 );
    
$randval = mt_rand( 0, sizeof( $imgArray ) - 1 );
    print(
"<IMG SRC=\"$imgpath/" . $imgArray[ $randval ] . "\">" );
?>
////////////////////////////////////////////////////////////////////////////////////////
Is it complicated ? Then let's comment the code.
///////////////////////////////////////////////////////////////////////////////////////
<?
    $handle
= opendir( "path/to/image/dir" );
    
$imgArray = array(); //the folder where the images are stored and then empties the array of images.
        
while($file = readdir($handle )){
            if(
$file != "." && $file != ".."){ //thgis up level dir
                
array_push( $imgArray, $file );
            }
        }
        
        
closedir( $handle ); //The code above starts a loop, reads folder contents and checks if the file is not a folder. Then a name of the file is stored in the array and folder is closed when the cycle is over.
        
$randval = mt_rand( 0, sizeof( $imgArray ) - 1 ); //This line generates a random value not greater than number of files in the directory.
        
print ("<IMG SRC=\"img/" . $imgArray[ $randval ] . "\">"); //Last step is to print image tag code to the page.
?>

 
Web Master : Safras Ahamed, Email : safras@ArabChat.Org
Copyright 2003 ArabChat Network