Randomize Background Image Using PHP

Randomize Background Image using php. Set up and array of filenames, which correspond to the file names of the images you are trying to randomize. At page refresh your visitors get to see a different background to your sites.

1. Above the DOCTYPE

redbackgroundSet 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 section

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>

About Bulent

Yes, my name is Bulent. I am originally from Turkey but now reside in United Kingdom. I have been working as a designer for over 8 years and have been very fortunate to have worked on a wide variety of projects. I have recently developed one of the most succesfull recruitment portal for nearly a million Turkish speaking community in UK within few months we had reached to nearly 65,000 users and stil growing. Thank you for stopping by!

Leave a comment

You must be logged in to post a comment.