Feature
Post

Category
Code


Random Images with PHP

Every now and then you want to randomize images, usually headers of sorts. This is pretty simple, with just 9 lines of PHP code you can rotate randomly between two images.

The PHP Script

Put this where you want to rotate your headers:

<?php
	$images = array(
	    0 => 'image1.gif',
	    1 => 'image2.gif',
	);
	$image = $images[ rand(0,(count($images)-1)) ];
	$output = "<img src=\"/mysite/randomimages/".$image."\" alt=\"\" border=\"0\" />";
	print($output);
?>

This will rotate between image1.gif and image2.gif, which are located in /mysite/randomimages/ on your server.

Adding more images is easy, just continue to add lines, starting with the next digit and has a corresponding file name, in the $images = array(); segment. This is the same code with five images instead of two:

<?php
	$images = array(
	    0 => 'image1.gif',
	    1 => 'image2.gif',
	    3 => 'hello.gif',
	    4 => 'monkeys.gif',
	    5 => 'ninjas.gif',
	);
	$image = $images[ rand(0,(count($images)-1)) ];
	$output = "<img src=\"/mysite/randomimages/".$image."\" alt=\"\" border=\"0\" />";
	print($output);
?>

Easy, isn’t it?

Now rotate those headers, photos, or whatnot!


  1. By Mary-Ann Horley posted on December 6, 2007 at 10:55 am
    Want an avatar? Get a gravatar! • You can link to this comment

    Is it possible to put Javascript instead where the filenames are?

  2. By Sjaq posted on December 6, 2007 at 11:08 am
    Want an avatar? Get a gravatar! • You can link to this comment

    You can do it faster by using
    $image = $images[array_rand($images)];
    Instead of
    $image = $images[ rand(0,(count($images)-1)) ];

  3. By nate posted on December 6, 2007 at 11:13 am
    Want an avatar? Get a gravatar! • You can link to this comment

    mt_rand(); is a better function to use instead of rand();. It’s better at generating a random number. There many many easy ways to do this.

  4. By Luke L posted on December 6, 2007 at 12:20 pm
    Want an avatar? Get a gravatar! • You can link to this comment

    Surely it would be easier to add new entries using:
    $images = array(‘photo1.jpg’,’photo2.jpg’);
    PHP automatically defaults to numbers starting at zero when no key is given.

  5. By tray posted on December 6, 2007 at 12:38 pm
    Want an avatar? Get a gravatar! • You can link to this comment

    how funny. i was JUST thinking yesterday “i need to find a clean and simple random image code” for my church’s webpage i’ve been working on this week. what perfect timing! thanks!

  6. By Nick Palacios posted on December 6, 2007 at 1:10 pm
    Want an avatar? Get a gravatar! • You can link to this comment

    Heres an even simpler method that will stay at 9 lines (-minus comments)

    <?php
    // Name your images like so 1.jpg, 2.jpg, 3.jpg, etc…
    // Change this to the total number of images in the folder
    $total = “11”;

    // Specifies Extensions
    $file_type = “.jpg”;

    // Location of folder holding images
    $image_folder = “images/random”;
    $start = “1”;
    $random = mt_rand($start, $total);
    $image_name = $random . $file_type;
    echo “”;
    ?>

  7. By Nick Palacios posted on December 6, 2007 at 1:12 pm
    Want an avatar? Get a gravatar! • You can link to this comment

    Correction

    Heres an even simpler method that will stay at 9 lines (-minus comments)


    <?php
    // Name your images like so 1.jpg, 2.jpg, 3.jpg, etc…
    // Change this to the total number of images in the folder
    $total = “11″;

    // Specifies Extensions
    $file_type = “.jpg”;

    // Location of folder holding images
    $image_folder = “images/random”;
    $start = “1″;
    $random = mt_rand($start, $total);
    $image_name = $random . $file_type;
    echo "";
    ?>

  8. By Nick Palacios posted on December 6, 2007 at 1:21 pm
    Want an avatar? Get a gravatar! • You can link to this comment

    Correction – Last Change I swear

    Heres an even simpler method that will stay at 9 lines (-minus comments)

  9. By Sjaq posted on December 6, 2007 at 2:59 pm
    Want an avatar? Get a gravatar! • You can link to this comment

    2 Line version:
    <?php
    $images = array('image1.gif', 'image2.gif', 'hello.gif', 'monkeys.gif', 'ninjas.gif');
    echo '';
    ?>

  10. By David Pennington posted on December 6, 2007 at 4:57 pm
    Want an avatar? Get a gravatar! • You can link to this comment

    Why is everyone making this require so much work? In PHP you should not have to deal with naming images a certain way… or manually entering the number.

    <?php

    $path = “images/”;

    //Use PHP to find the images
    foreach (glob($path. “*.jpg”) as $imagename) {
    $images[] = $path. $imagename;
    }

    print ”;

    ?>

    Just drop the above script into a file and it will grow with the number of images in the directory. You will never have to mess with the file again!

    ;)

  11. By David Pennington posted on December 6, 2007 at 4:59 pm
    Want an avatar? Get a gravatar! • You can link to this comment

    Why is everyone making this require so much work? In PHP you should not have to deal with naming images a certain way… or manually entering the number.


    <?php

    $path = "images/";

    //Use PHP to find the images
    foreach (glob($path. "*.jpg") as $imagename) {
    $images[] = $path. $imagename;
    }

    print '';

    ?>

    Just drop the above script into a file and it will grow with the number of images in the directory. You will never have to mess with the file again!

  12. By David Pennington posted on December 6, 2007 at 5:01 pm
    Want an avatar? Get a gravatar! • You can link to this comment

    That is sad – my post was killed by your editor.

    You really need to fix your comment editor so that code in ‘<code>’ tags doesn’t get deleted.

  13. By TDH posted on December 6, 2007 at 6:32 pm
    Want an avatar? Get a gravatar! • You can link to this comment

    Great tips here! And of course you can squeeze it all together, but it’s not so easily read then, especially for people not accustomed to PHP syntax.

  14. By Nico Zwemstra posted on December 7, 2007 at 2:08 am
    Want an avatar? Get a gravatar! • You can link to this comment

    If you’re using a MySQL database for your website, you could also use a SQL query to get a random image. Put the image locations in a table and execute a query like this:

    SELECT * FROM table_name ORDER BY RAND() LIMIT 1

  15. By ibanez182 posted on December 7, 2007 at 4:45 am
    Want an avatar? Get a gravatar! • You can link to this comment

    I use this half line of PHP to do that. If for example the name of the
    files are something like:

    background_01.jpg,
    background_02.jpg,
    background_03.jpg
    an so on…

    i write:

    <img src="./images/background_0< ?php rand(1,3) ?>.jpg" alt="">

    where 1 is the first image and 3 is the last.
    I think it’s so easy

  16. By Matthew Griffin posted on December 7, 2007 at 9:02 am
    Want an avatar? Get a gravatar! • You can link to this comment

    Great mini-tutorial. This is something I use quite often so I know the PHP novices will be glad to snatch it up.

  17. By Armen posted on December 8, 2007 at 8:40 am
    Want an avatar? Get a gravatar! • You can link to this comment

    The randomizer script from A List Apart is the easiest way of doing it, in my opinion. You don’t have to alter anything, or change image file names, it just works out of the box. Which is why I’m using it for my Bedrock Grid WordPress theme.

    I’ll keep this in mind though, Thord.

  18. By Travis posted on December 20, 2007 at 6:44 pm
    Want an avatar? Get a gravatar! • You can link to this comment

    How could you make those images links? Say you had a store that randomly show an item. How could you make it so you could click the items picture and go to the dedicated page for that item?

  19. By Mukesh posted on February 21, 2008 at 7:15 am
    Want an avatar? Get a gravatar! • You can link to this comment

    the array above in the code has a little mistake.. the key 2 is missing. so, when the key 2 appears then no image is displayed.

    the actual form of array should be ::

    $images = array(

    0 => ‘image1.gif’,

    1 => ‘image2.gif’,

    2 => ‘hello.gif’,

    3 => ‘monkeys.gif’,

    4 => ‘ninjas.gif’,

    );

  20. By nAcho posted on March 16, 2008 at 3:59 pm
    Want an avatar? Get a gravatar! • You can link to this comment

    Great and simple code. Thanks

  21. By Chris posted on April 3, 2009 at 11:52 pm
    Want an avatar? Get a gravatar! • You can link to this comment

    Mukesh:

    Thanks for pointing that out. I was struggling to figure out if I had suddenly turned PHP-stupid, but it was just a numbering thing.

  22. By Jamie Dunbar posted on July 2, 2009 at 1:22 pm
    Want an avatar? Get a gravatar! • You can link to this comment

    Hi guys.

    I want to get a random file name from a directory which i seem to have managed to do.

    it comes back as daXXXXXX.jpg

    I want to then just have the XXXXXX bit, to plug into this

    echo $car = new ImageObject(XXXXXX);

    Any ideas?

  23. By ilias posted on July 13, 2009 at 5:49 am
    Want an avatar? Get a gravatar! • You can link to this comment

    i want to show 5 images in a page randomly, but one should not match the other image. is it possible? please help me.

  24. TrackbackRandom Images with PHP - Find Motivetomlovesyou | Random Images With PHPSunday Weekly Roundup #17 - 12/09/2007 » Blog at veanndesign.comSeth Holladay » Links » links for 2007-12-28