In this tutorial we will create a random image generator. This could be useful for rotating banner, ads, traded button links or just simply randomizing your pictures. This tutorial is based from this PHP snippets that I created a while ago. Ok lets get started!
Below is the function to view all our images from a specific directory. Make sure that only images are on your folder or else it would also be included on randomizing.
//Function start function viewfiles($path){ //Create a blank array $ff = array(); //Open directory if ($dir = @opendir("./$path")){ //Make sure file exist while (false !== ($file = readdir($dir))) { //Make sure we dont include the "." and ".." file if ($file != "." && $file != "..") { //Put all images into the array we create above $ff[] = $file; } } //Close directory closedir($dir); } //Use the implode function to put all images together $result = implode("*",$ff); //Return all files that has been "imploded" return $result; }
The function above will open the specific folder, put all images into an array and put them all together using the implode function.
Below we will use the above function to display all images from our directory and then use array_rand function to randomize our images.
//Actual path to your image directory $dir_path = "imgs"; //Use our a viewfiles() function to display images $dir = viewfiles($dir_path); //Use the explode function to separate images $exp = explode("*",$dir); //Randomize our images srand((float) microtime() * 10000000); //Use the array_rand function to randomize our images $pic = $exp[array_rand($exp)];
Make sure you change the $dir_path variable to the actual path of your images. The above code will use our viewfile() function to diplay our images and then randomize them using the array_rand function. Now all we have to do is to display our images!
Ok the code below will display our random images!
echo "<a href=\"$dir_path/$pic\"><img src=\"$dir_path/$pic\" border=\"0\" alt=\"\"/></a>";
Not much to explain on the code above. Basically we are using all variables from the randomizing part.
Ok lets put all the code together!
<?php function viewfiles($path){ $ff = array(); if ($dir = @opendir("./$path")){ while (false !== ($file = readdir($dir))) { if ($file != "." && $file != "..") { $ff[] = $file; } } closedir($dir); } $result = implode("*",$ff); return $result; } $dir_path = "imgs"; $dir = viewfiles($dir_path); $exp = explode("*",$dir); srand((float) microtime() * 10000000); $pic = $exp[array_rand($exp)]; echo "<a href=\"$dir_path/$pic\"><img src=\"$dir_path/$pic\" border=\"0\" alt=\"\"/></a>" ?>
Well all you have to do now is to change the path to your images and use the code above and that should display your random images. I hope you learn something from this tutorial, remember if you have any questions just post in our forums. Good Luck!