Random Background Images Using PHP on Page Refresh

Changing background images randomly adds interaction to a website. Just make sure that you keep the branding of your site. One method to do this is using php code.

The code below works by choosing the background image from a list of images in a directory. Once chosen, the image will be used in the CSS to set as the background image. Make sure that you put all of this code inside the <head> tag.

  $image_location = array('images/bg.png', 'images/bg2.png', 'images/bg3.png' ); // array of image file location

  $i = rand(0, count($image_location)-1); // generate random number size of the array
  $the_bg = "$bg[$i]"; // the selected background image

After this, use CSS to get the URL of the background image.

<style type="text/css">
	background: url(<?php echo $the_bg; ?>) repeat-y center top transparent;

It works like the usual CSS code and you can modify it except for the php code for the URL of the background image.

*Some links may contain affiliate links. I may get small commission from your purchases to fund this website and to avoid annoying ads.