Subscribe to Tutorial Feed

Flash and PHP Bible

The Flash and PHP Bible has been released! The book can be found on Amazon or wherever fine books are sold in your area.

The Flash and PHP Bible has a forum for quick support.

Scriptplayground » tutorials » php » Random Image Loader

Random Image Loader

Display a random image via PHP

Relative path to the images, if the files are in the same directory leave it blank.

$img_folder = '';

Array of allowed image types, seperate each with a "|" character

$extensions = 'jpg|jpeg|png|gif';
$extensions = explode('|', $extensions);

Assign the file array and set the folder if needed

$files = array(); 
if($img_folder == '') 
	{
	$img_folder = './';
	}

Open the directory and start traversing through the directory, check the extension type and if it is good, increment "$x"

$handle = opendir($img_folder);
while(false !== ($file = readdir($handle))) 
	{
	foreach($extensions as $extension) 
		{
		if(preg_match("/\." . $extension . "$/x", $file)) 
			{
			$files[] = $file;
			$x++;
			}
		}
	}

We have finished searching through the directory, so lets close it

// Close the directory handle
closedir($handle);

Generate a unique seed for PHP 4.2 and earlier

if(phpversion() < "4.2")
	{
	mt_srand((double)microtime()*100000);
	}

Finally send the image url to the browser

print $img_folder . $files[mt_rand(0, $x-1)];

To display the img, just apply some "img" tags on your site and point to this php page

<img src="PATH/TO/FILE.php" alt="" />

Here is the completed code for easy copy & pasting.

// PHP Image Rotator
// simply drop this PHP into a folder of images
// and call it with a little HTML
// Usage: <img src="PATH/TO/rotator.php" alt="" title="" />

$img_folder = '';
$extensions = 'jpg|jpeg|png|gif';
$extensions = explode('|', $extensions);
$files = array(); 
if($img_folder == '') {
  $img_folder = './';
}
$handle = opendir($img_folder);
while(false !== ($file = readdir($handle))) {
  foreach($extensions as $extension) {
    if(preg_match("/\." . $extension . "$/x", $file)) {
      $files[] = $file;
      $x++;
    }
  }
}
// Close the directory handle
closedir($handle);
if(phpversion() < "4.2") {
  mt_srand((double)microtime()*100000);
}
print $img_folder . $files[mt_rand(0, $x-1)];

That is the end of the article. If you have any questions or comments, feel free to post them below..

Follow Scriptplayground on Twitter (@scriptplay)

Comments: Random Image Loader

 D.S  Sun Feb 5, 2006 4:31 am  
Thankz.. I Was Looking For Something Like This ;)
 mkeefe  Sun Feb 5, 2006 7:16 am  
Glad you liked it and thanks for commenting.
 mex  Sat Jun 17, 2006 5:17 am  
this is difficult but i'm hoepful to get it done. wish to have a full code too. btw, i love this template and the way the comments are arrange.
 mkeefe  Sat Jun 17, 2006 8:07 am  
I have added the "complete" code to the article and appreciate the feedback.
 Mex  Sat Jun 17, 2006 2:10 pm  
yeah thats so nice of you. i realize that i have to add one by one after seeing the other tutorials. thanx buddy.
 mkeefe  Sat Jun 17, 2006 6:56 pm  
I am working on a different approach where all tutorials will have full code at the beginning and then go into the process of explaining each step. Scriptplayground V3 is in beta and will be released pretty soon with that addtion among many other features.
 drixie  Sat Apr 28, 2007 3:51 pm  
nice script. although i would like an external php script that randomly displays flash movies.
 mkeefe  Sun Apr 29, 2007 7:45 am  
That is possible, it would just require some more code and I would probably use XML to store that SWF information. Doing so would allow the script to have info like width, height, bgcolor, fullscreen, etc all easily accessible.
 The Merg  Sun May 13, 2007 4:55 am  
Looks very simple to use, but I have one question. Is there a way to have the script search through subdirectories off of the image path that is specified? I also like how you broke down the code and explained it all.
 mkeefe  Mon May 14, 2007 1:53 pm  
The script doesn't have that functionality at the moment, but you could simply write a recursive scanner that would grab the contents of the directory. Basically you would use is_dir() to determine if a scan is needed and then process each file.

This would of course take more time and on larger directories would cause a strain on the server, so use it with caution.
 volcomhackzor  Tue Nov 20, 2007 3:14 pm  
it works if i open the php file from my browser, but wont load in my html file...

http://ms.servebeer.com/stuff is where the files are located

volcomhackzor@inbox.com is my email

thnx for teh script
if you need ftp access to my stuff dir i can give it to you
 mkeefe  Tue Nov 20, 2007 3:52 pm  
Remove the "./" in the image file and see if that works.. some servers choke on the "./" in a file path.
 Dcameraman  Thu Feb 21, 2008 3:22 pm  
Another way to do it would be to have a folder with image 1.jpg, 2.jpg, etc. . .

Then all you do is:


1 and 25 are included.

It requires that you rename all of your images, but it really is simple.
 mkeefe  Thu Feb 21, 2008 4:50 pm  
That is a good option for a couple of images, but sometimes it is required that an image be named something important. Either way, whichever way works for you is the best option.

Sorry about your code being displayed, I am in the process of revamping the system to allow BB or Textile properly.
 sluce  Tue Mar 4, 2008 3:44 pm  
Hiya,

I have a bit of a problem... I am running a php script for my site in which I have 13 cells bordering the sides of my pages. What I want is to randomly select 1 of 13 images each onload or page refresh for each of the 13 squares/cells.

Currently I am running it in such a way that I have 13 different directories each with a copy of the php script inside and my 13 different images. This does not create my desired effect.

What i want is to have all 13 images from my directory load at random into these 13 squares/cells with the images changing squares on page refresh/onload each time without ever repeating the same image twice on the page...

I don't know if I'm explaining myself very well, but I've been trying to find a solution to this for weeks and I desperately need some help...

Any suggestions would be greatly appreciated...

My website: www.scenewatch.co.uk
 mkeefe  Tue Mar 4, 2008 7:45 pm  
@sluce, What I would recommend for that is a PHP file that loads all of the files into an array. Then randomize that array and use a for..loop to draw the table cells using the randomized array.

You could use the while..loop portion of this script to build the array and then just implement the remainder of the script using standard PHP functions.
 sluce  Wed Mar 5, 2008 6:30 am  
@mkeefe, I have to be honest and say that I've never done a website as complex as the one I'm currently working on.

I've never used php before and it was mission just to create what I have at the moment... I am not a programmer or web designer... and I have to admit that I currently have no knowledge of what an array is or any knowledge ofthe reference you make to for..loop / while..loop.

I had alot of help from a friend who has very simple and basic knowledge f php to create the file I am currently using shown below.

Is this going to be something I should out-source to someone more knowledgeable than myself or would you be willing /able to give me some simple instruction?

I thank you in advance as I know it's your valuable time and effort I'm asking. I appreciate the fast response.

CHEERS!



$folder = '.';


$extList = array();
$extList['gif'] = 'image/gif';
$extList['jpg'] = 'image/jpeg';
$extList['jpeg'] = 'image/jpeg';
$extList['png'] = 'image/png';


$img = null;


if (substr($folder,-1) != '/') {
$folder = $folder.'/';
}


if (isset($_GET['img'])) {
$imageInfo = pathinfo($_GET['img']);
if (
isset( $extList[ strtolower( $imageInfo['extension'] ) ] ) &&
file_exists( $folder.$imageInfo['basename'] )
) {
$img = $folder.$imageInfo['basename'];
}
} else {
$fileList = array();
$handle = opendir($folder);
while ( false !== ( $file = readdir($handle) ) ) {
$file_info = pathinfo($file);
if (
isset( $extList[ strtolower( $file_info['extension'] ) ] )
) {
$fileList[] = $file;
}
}
closedir($handle);


if (count($fileList) > 0) {
$imageNumber = time() % count($fileList);
$img = $folder.$fileList[$imageNumber];
}
}
if ($img!=null) {
$imageInfo = pathinfo($img);
$contentType = 'Content-type: '.$extList[ $imageInfo['extension'] ];
header ($contentType);
readfile($img);
} else {
if ( function_exists('imagecreate') ) {
header ("Content-type: image/png");
$im = @imagecreate (100, 100)
or die ("Cannot initialize new GD image stream");
$background_color = imagecolorallocate ($im, 255, 255, 255);
$text_color = imagecolorallocate ($im, 0,0,0);
imagestring ($im, 2, 5, 5, "IMAGE ERROR", $text_color);
imagepng ($im);
imagedestroy($im);
}
}
?>
 Ben  Fri Mar 7, 2008 11:36 am  
I seem to have a problem with the code, i click on the html page it displays the box with the cross in it, and when i go on the php file it comes up with a blank page apart from ./ in the top corner
 mkeefe  Fri Mar 7, 2008 3:54 pm  
That sounds like the PHP is loading a none image file, can you provide more info on the script/server version and all, so I can
better help you get this solved.

Let me know,

Matt
 mkeefe  Fri Mar 7, 2008 3:55 pm  
@sluce, If you don't understand how the code is working, it may be best to hire someone. For the simple fact of, you should know what the script is/isn't suppose to do, in the interest of security.
 Njose Augustine  Tue May 27, 2008 9:07 am  
Hey, thanks alot for the script.
I just have one query. Could you help me differentiate between the PHP 'print' command and the PHP 'echo' command. I can see you used the print command instead of echo??
I have been using the language to develop dynamic web applications for 2years now and I have no idea what secret is behind their making.
Thanks!
 mkeefe  Tue May 27, 2008 9:17 am  
@Njose,

That is a great question! This is the best answer I have found:

http://www.faqts.com/knowledge_base/view.phtml/aid/1/fid/40
 Tim  Wed Jun 11, 2008 1:30 pm  
I am trying to implement this code that you have supplied here, with limited success.

The code works if I view the rotator.php page in my browser, but it does not work on the page I need it on.

I tried to remove the ./ as suggested in a post already . . . this had no effect; other than to make it not work on the rotator.php page either.

I am baffled . . . which really doesn't take much. Any ideas on how to make the code work properly in this case?

The suggestion to change the file names to numerical extensions seems to missing some key insturctions, a red "x" in a box is displayed in the post.
 mkeefe  Wed Jun 11, 2008 2:24 pm  
@Tim, If you are running the example with limited success I recommend you use the full path "http://mysite.com/rotator.php" because that is most likely the problem.

If not, let me know I am glad to help.
 Tim  Thu Jun 12, 2008 4:49 am  
I have the full path typed in.

I even tried to replace the ./ with the full path to the image folder hoping that it would tack the image file onto the end of that . . . that didn't work either. (that broke it all together)

I checked the permissions for the files on the server thinking maybe there was a permission problem. I made sure they were all set to allow reading, writing . . . the whole 9 yards.

I know the php file is working, I am not sure if the problem is in not being able to access the php file to begin with, or if something is not allowing the file to run all the way through to the end.
 mkeefe  Thu Jun 12, 2008 6:20 am  
@Tim, Just curious, did you set the server path eg: "/home/vhosts/web/etc..." or a web path "http://pathtosite.com"?

Just trying to figure this one out. :)
 tim  Thu Jun 12, 2008 9:15 am  
I used the web path.
 tim  Fri Jun 13, 2008 10:08 am  
I am still banging my head against the wall trying to figure this out.

I am running the website on Apache with PHP 4.4.2.

If I replace the print command with a print command containing the path to a single image, it still does not display the image. If I type the path into a browser directly, it displays the image; so I know the path is correct.

Something is keeping it from making the connection to the page where I want the images to display.

If I type the path in the img tag directly into the browser address bar . . . it displays the php page and the resulting code.

Any additional ideas?
 mkeefe  Fri Jun 13, 2008 10:34 am  
Can you email me a link to the page its not working on, and copy the php file, change the extension to "phps" so I can look at the source code.
 Cibertrix  Thu Jul 10, 2008 2:29 am  
same problem here as tim is having - I am also using Apache but with a later php version...

if I enter a correct path to an image of course the image is found, but using the very same path to the rotator.php file does not produce any effect other than image missing - the path is correct though - something is amiss.

Cheers
 chevy  Sun Sep 21, 2008 6:03 pm  
Would it be possible to add a target path to the image. I want to load a random image link.

Thanks
 Mike  Mon Jan 12, 2009 5:40 pm  
So im trying to display random images. On the site there will be lots of diffrent sponser logos but only three will be displayed. However in this example i have three pics 1.png 2.png and 3.png and im trying to make to random and diffrent ones appear.
some times it works and then other times i get the white box with the x in the middle indicating the file cannot be found. The pics are in the same directory, and here is my code:


<?php

//Extension gose here including the dot "."
$extension = ".png";
//Pic Names go here, Do not include extension
$sponsers= array (
"1" ,
"2" ,
"3" ,
);

//number of images
$maxnumber = 3;

$pic1 = mt_rand (0,sizeof($sponsers));

$img = $sponsers[$pic1] . $extension;

print $img;

print("<img src="$img"><br>n");

unset ($sponsers[$pic1]) ;

$sponsers =array_values($sponsers);

$pic2 = mt_rand (0,sizeof($sponsers));

$img2 = $sponsers[$pic2] . $extension;

print("<img src="$img2"><br>n");

?>
 Mike  Mon Jan 12, 2009 5:55 pm  
actually here you can look at the page yourself:

http://sgi-clan.info/test/test1.php
 Mike  Tue Jan 13, 2009 6:18 pm  
I got it working! Ill post the code below, if you want to see this in action go to http://sgi-clan.info/test/test2.php its nothing special though.


<?php

/*
NOTE THIS: Because the way this program works you must use numbered files.
YOUR FIRST FILE MUST START AT 0.yourextension. AND YOU MUST GO IN NUMARICALLY ORDER/
So if you have six pics, you name your pics you name them 0-5 and create the array with
values 1,2,3,4,5.

*/

//Extension gose here including the dot "."
$extension = ".png";
//Pic Names go here, Do not include extension
$sponsers= array (
"1" ,
"2" ,
"3" ,
"4",
"5",
"6",
);

//number of images
$maxnumber = 3;

$pic1 = mt_rand (0,sizeof($sponsers));

$img = $pic1 . $extension;

print("<img src="$img"><br>n");

unset ($sponsers[$pic1]) ;

shuffle($sponsers);
$pic2 = mt_rand (0,sizeof($sponsers));

$img2 = $pic2 . $extension;

while ($img2 == $img)
{
$pic2 = mt_rand (0,sizeof($sponsers));
$img2 = $pic2 . $extension;

}

print("<img src="$img2"><br>n");

?>
 Gary  Mon Apr 20, 2009 9:57 pm  
I tried mkeefe's example above and all it displays is #.gif. It's randomly generating, but showing the name of the image, vice the image itself. Did I mess the code up or is it my server?
 mkeefe  Tue Apr 21, 2009 4:35 am  
@Gary - Make sure you print/echo the filename into an IMG tag like you would use for any standard image.
 arti  Sat Apr 25, 2009 11:48 pm  
I not found it. I want to image preloader script. Content loader working first and then loaded image, loader closing and image view. Help me please.
 mkeefe  Mon May 4, 2009 6:56 am  
@arti - I recommend you pick up the basics of ActionScript 3 first, then work on that project once you have the foundation.
 Andy Koop  Wed Sep 9, 2009 5:57 am  
Are there any problems with using this technique in an https directory? I can't seem to make the images show up.
 Andy Koop  Wed Sep 9, 2009 7:12 am  
I was able to solve the problem by using your "Building a Smarter..." tutorial. Thanks!
 cinsel sağlık  Mon Dec 19, 2011 7:27 am  
Building a Smarter... tutorial. Thanks!
 kiralama  Fri Feb 10, 2012 3:49 am  
Building a Smarter... tutorial. Thanks! +1
Add a comment
The ability to add new comments has been disabled in this archived version.

Loading
Main | Tutorials | Articles