Code Snippet

Home » Code Snippets » PHP » Randomize Background Image

Randomize Background Image

1. Above the DOCTYPE

Set up and array of filenames, which correspond to the file names of the images you are trying to randomize.

<?php
  $bg = array('bg-01.jpg', 'bg-02.jpg', 'bg-03.jpg', 'bg-04.jpg', 'bg-05.jpg', 'bg-06.jpg', 'bg-07.jpg' ); // array of filenames

  $i = rand(0, count($bg)-1); // generate random number size of the array
  $selectedBg = "$bg[$i]"; // set variable equal to which random filename was chosen
?>

1. CSS in the <head>

Normally you'd want to keep CSS out of the HTML, but we'll just use it here to echo out the random file name we selected above.

<style type="text/css">
<!--
body{
background: url(images/<?php echo $selectedBg; ?>) no-repeat;
}
-->
</style>

Subscribe to The Thread

  1. Antti

    You could probably do with even shorter code:

    <!–
    body{
    background: url(images/bg-0.jpg) no-repeat;
    }
    –>

    ..if there are under 10 images.

    • ??? I’m unsure about your method here. Where would you implement the php?

    • Antti

      Uh-oh, something seems to have gone wrong when I submitted that message. I meant:

      background: url(images/bg-0

      .jpg) no-repeat;

      This works of course only if there are <= 10 images.

      Let's see, if it works this time…

    • Yeah I assumed there was some inline PHP going on there. PHP tags get stripped from WordPress comments, so if you need to post them, put a space between like this < ?

    • Antti

      OK,

      so one more time (you probably already guess where I’m going here):

      background: url(images/bg-0.jpg) no-repeat;

      Like that!

    • lol :P

  2. Michael

    Great snippet! How would I pull the images from a folder (and adds or subtracts from the list everytime the user uploads or deletes a photo from that directory)?

    mz

    • Did you already find out how you can extract images from a folder?

    • you can use the glob function, for example :

      you have a folder name ‘image’ this how is in action

    • Sorry forgot the code :

      
      
      function randImage($path)
      {
      	if (is_dir($path))
      	{
      		$folder = glob($path); // will grab every files in the current directory
      		$arrayImage = array(); // create an empty array
      
      		// read throught all files
      		foreach ($folder as $img)
      		{
      			// check file mime type like (jpeg,jpg,gif,png), you can limit or allow certain file type
      			if (preg_match('/[.](jpeg|jpg|gif|png)$/i', basename($img))) { $arrayImage[] = $img; }
      		}
      
      		return($arrayImage); // return every images back as an array
      	}
      	else
      	{
      		return('Undefine folder.');
      	}
      }
      
      $bkgd = randImage('image/');
      $i = rand(0, count($bkgd)-1); // while generate a random array
      $myRandBkgd = "$bkgd[$i]"; // set variable equal to which random filename was chosen
      
      
      
  3. I wrote this one for a client. Works well. It returns the path to a random image. In addition it won’t allow the same image to load twice consecutively .

  4. I guess I’m not allowed to post a hyperlink on my comment above. – Sorry about that.

  5. ryan

    this is not working for me for some reason…

  6. Hey thanks for this php-code/css it works great now, just modified the css a little bit and it was exactly the code i needed! :) Cheers

  7. And much better is give random class to body, and define backgrounds in main css file.

  8. Hello and thanks for sharing this…

    I will like to ask if this example is to apply a random image on the body? right?
    can I apply this to a #div? How I should do it?

    Blessings.
    Rai.

  9. barun

    hello, i am little confused here.. could u please help me.. i didn’t know where to put the php file.. please help… thank you

    • Gutem

      You have to put on your header.php, if you’re using one.
      The first code block you put ABOVE the DOCTYPE.
      The second code block you put before tag

  10. lol: i think your scripts are not working properly.these are copy paste form net and you never use these

    • Navee

      No my friend… $you = $followed_instructions;

      IF ($followed_instructions === true) {
      $result = “this works as written and intended “;
      $result .= “…and by reading the code ALONE without execution it works”;
      IF ($you === “are PHP aware”) { >>>NICE_SMILEY
      [h1]AWE GIVE ME THOSE CHEEKS…LOOKS LIKE SOMEONE IS GETTING A STICKER!!! [/h1]
      NICE_SMILEY;
      }
      }else{
      $result = “{$you} will assume it’s copy/paste and non-working “;
      $result .= “and that nested IF may throw you FOR a loop…and WHILE may DO more harm to you…WITH ($your_assumption) {$return false;} #JS”;
      }

      $message = “Either way…”;

      echo $message . ” ” . $result . “!”; // or use print IF echo is too copy/pasty for $you…please TRY this snippet again until you CATCH random background images appearing in your browser. #TeamHelloWorld

  11. hello, I’ve tried to implement this but for some reason it’s not working. I added the php above my doctype in my index.php page and added the php echo command inside my background tag in the css. I’m just getting a blank screen? Any help would be appreciated : )

    • Navee

      While your screen is blank: right-click and select View Background image or equivalent to viewing background image depending on your browser! You may get an error message stating the image you are trying to preview is not available.

      I.e. wrong file path, incorrect spelling, etc. >>> double check your image file names in the php document (within the $bg ARRAY) with the file names of the images in your folder…and make sure your CSS background url image path is set correctly. Sometimes people have “image” dir (singular) and others have “images” dir (plural) or further nested image folders.

      It does not matter where your images are so as long as you point to the exact directory and have the correct spelled file names in your ARRAY it should work.

      Also it may seem obvious but make sure you ARE using a webserver capable of parsing/executing php code…other than that it is normally file paths or misspellings. But I’m sure you have ALL the above right…right? Then make sure you end your extension with .php rather .htm or .html and watch it WORK!!!

  12. Hi!
    the code from the post worked for me ;)

    many thanks,
    AF

  13. It worked for me. Thanks. I use a css-file and it worked perect. I used the coce in a table.

Speak, my friend

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
~ The Management ~