Tutorial – Pull in a Random Image from a Folder with PHP

I came up with an idea for a client where instead of just pulling in the newest image in a file my code would pull in a random image from a folder. This serves two purposes:
1) Gives visitors the feeling of a page that gets updated and gives them something different to look at when they visit the website again.
2) It also changes the code which shows the page as being updated to spiders and other search engine bots. (To what degree this will help your SEO remains to be seen but likely on par with doing minor updates to your website)

Now how to get this done? Well I looked around and there were a lot of different ways to code it some from using things as simple as echoing an image name with a random number genrator attached to the end of the file name before the extension for example:

  1. <img src="image/filename_<?php echo rand(0, 2); ?>.jpg" alt="" />

To things that would be much more in depth and involved 20+ lines of code. The problem with all the code I found is that they were limited by having to define the file type and/or manually define how many images were in the folder.

Now here’s what I came up with for my random image generator:

  1. <?php
  2. $dir = ‘images/’;
  3. $images = scandir($dir);
  4. $i = rand(2, sizeof($images)-1);
  5. ?>
  6. <img src="images/<?php echo $images[$i]; ?>" alt="" />

That’s all the code I needed… 6 lines of code. This code scans a directory, generates a random number with a maximum set by the amount of files in directory. Then it prints out an image within the defined directory. This allows you to add as many or as few images to the folder as you want without ever changing the code.

Lets break it down:

  1. <?php
  2. $dir = ‘images/’;
  3. $images = scandir($dir);

This first section is doing 2 things:
1) Defines the directory for the images.
2) Creates an array of the defined directory.

Now that we have the files defined in an array lets create a random number generator:

  1. $i = rand(2, sizeof($images)-1);

This line of code is doing 3 things:
1) The obvious part is it generates a random number with rand.
2) We’re restricting it to start at 2 because 0 and 1 are always the directories (0 = ‘.’ and 1 = ‘..’)
3) We’re restricting the maximum number to the number of the array and subtract 1 from that to account for the fact that the array itself starts at 0, while the code”sizeof()” starts counting with 1 instead of 0.

The last part of the code is what will actually be visible in the HTML/XHTML:

  1. <img src="images/<?php echo $images[$i]; ?>" alt="" />

This is spitting out the file name that was randomly picked from the array using the random number we generated.

Update: You could even make the alt tag spit out the name of the file by changing the last line to this:

  1. <img src="images/<?php echo $images[$i]; ?>" alt="<?php echo str_replace(array(‘.jpg’, ‘.png’, ‘.gif’), ”, $images[$i]); ?>" />

This is simply replacing the possible file extensions with nothing so that the alt tag will say “filename” instead of “filename.jpg”.

17 Responses to “Tutorial – Pull in a Random Image from a Folder with PHP”

  1. Emanuela says:

    Thanks for creating this. I tried to use it(I am not knowledgeable on PHP) but it doesn’t show the images. Also is it possible to save the PHP code on a separate file instead of putting on the head of the html file so that I can use the same PHP in different pages? How do I do that? How do I link it?

    Thanks,
    Emanuela

  2. Robert Heck says:

    The code is actually self contained and can go anywhere in a page it doesn’t necessarily have to go in the header.

    As long as you have a folder labeled images (you could change this in the code) in the same directory as the file with this code it should pull the images from there.

    I’m not sure why it wouldn’t be working but did you make sure the file with the code has a .php extension if it doesn’t already.

    As to making it its own code that you could include in multiple files, you can add the code to it’s own file for example “image-puller.php” and then you’d add this line:
    < ?php include("file_location/image-puller.php") ?>
    Note: file_location refers to the actual file location in case you put it into a sub folder if not you can just leave that out.

  3. BOHK says:

    Thanks for the code but i can’t get it to work ether.
    I don’t know what in doing wrong.
    Any help would be appreciated.
    Thanks

  4. Tom says:

    I tried everything I could think of and no show. As written it leaves me with a blank page. Seems something is missing….

  5. Diego Pereira says:

    change the quotes on line 2, they do not make the code work

    <img src="images/” alt=”" />

  6. Robert Heck says:

    Are you just copying and pasting the code? As Diego pointed out there’s an issue with the way single quotes are showing up in the post I made (line 2 in the whole code section). If you’re not using a text editor with syntax highlighting this could get missed. Replace those single quotes if you’re copy/pasting instead of writing it out and the code should work.

  7. Robert Heck says:

    Are you just copying and pasting the code? As Diego pointed out there’s an issue with the way single quotes are showing up in the post I made (line 2 in the whole code section). If you’re not using a text editor with syntax highlighting this could get missed. Replace those single quotes if you’re copy/pasting instead of writing it out and the code should work.

  8. BOHK says:

    I tried again and get this
    Error: The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must be declared in the document or in the transfer protocol.

  9. Robert Heck says:

    The only reason I can think that kind of error is appearing is if you’re not including the standard HTML code as well. I could be wrong but to be sure could you post all of the code of your test on Pastebin so I can get a better idea?

  10. Tom says:

    I got it to work. Just another example of how much I need to learn about working with php…..

    Question – Is there a way to go deeper then one folder?
    I have images in a folder AND a folder within that folder. Can’t change that, wish I could.
    Right now the code is pulling from the main folder but not the folder within that main folder.

    Thanks for the code and the help.
    Tom

  11. Robert Heck says:

    You can go about it many ways but the simplest is to make another set of code that is looking into that folder. You’d just have to make a few changes, here’s an example:
    <?php
    $dirTwo = 'images/new_folder/';
    $imagesTwo = scandir($dirTwo);
    $j = rand(2, sizeof($imagesTwo)-1);
    ?>
    <img src="images/new_folder/<?php echo $imagesTwo[$j]; ?>" alt="" />

    The variable names can be whatever you want and make sure to change “new_folder” to whatever that folder’s name actually is.

  12. Bill says:

    Tom, can you post your code by page

  13. Tom says:

    #Robert Heck ,
    Great. Works nice. I was also able to link the images. I have also placed the code into a separate page to keep my main page un-cluttered and keep css separated for easy editing. Not sure if that is good practice but I like that if an error develops the main page will keep loading.

    Thank you very much.

    #Bill,
    My code is same as what Robert posted except I changed to my directories, etc.
    I.E.
    Where $dir = ‘images/’; = Mine: $dir = ‘oc-content/uploads/0/’;

    Note that I am working on localhost. Site is not yet live.
    Tom

  14. Bill says:

    This is what I have.
    on my html page I have the
    <img src="images/” alt=”" />
    and then I have a folder labled Images and in that folder I have

    saved as a .php
    with jpeg images in it what am i doing wrong
    Thanks

  15. Bill says:

    Part of it did to post –
    and then I have a folder labled Images and in that folder I have
    line 1-5 from your original code and its
    saved as a .php

  16. Tom says:

    @Bill,
    If you were directing your post at me, I’m sorry but was out of town a few days.

    I created a php file with code to display 2 pictures. I named it today.php. I created a link to this file in my main page sidebar.
    I.E.:

    I inserted the following code into my taday.php file:

    <a href="”>
    <img src="oc-content/uploads/0/” alt=”" height=”100″ width=”125″ />

    <a href="”>
    <img src="oc-content/uploads/1/” alt=”" height=”100″ width=”125″ />

    Using above code starting and ending with “First set”
    $dir = ‘oc-content/uploads/0/’;
    Above is the directory where the images are located on MY site.

    <a href="”>
    Above is my link to show a new image each time the page is loaded.

    <img src="oc-content/uploads/0/” alt=”" height=”100″ width=”125″ />
    Above is location of images on MY site and the size settings to display the image.

    Because I wanted 2 different pictures to load each time I duplicated the code but pointed each to a different folder.

    Not sure if this helps because I have edited the code to suit my wants.

    Tom

  17. Tom says:

    @Bill,
    I see we are unable to post actual code on this site so my last post makes no sense….. No sure how to answer or help.

    Tom

Leave a Reply