Randomise A Website banner With PHP
This tutorial will show you how to create a randomized banner image for your website using just 1 line of php. This is exactly the same as the technique as I am using on this site. To see it in action simply refresh the page a few times
Your Images
To start things off create a new folder called banners, inside of this you want to put your banner images all should be the same size, for example 700px x 100px. Name the banners 1.jpg, 2jpg, 3.jpg etc for however many you want.
The Code
this will only work on a .php page, so make sure that whatever page you apply this to you use the correct extension.
<img src="images/banners/<?php echo(rand(1,3)); ?>.jpg" alt="a banner" />
The code itself is pretty straight forward, all we are doing is creating the pathway to the banners in a standard <img src> tag.
Then when we get to the banner name we use PHP’s rand() function to randomise the image. This is why we have names our images 1, 2, 3.
As you can see the first argument passed in is the 1 number for the rand function to start on. The argument is the maximum number the function should randomize between. In this case 3, but you can make this whatever you like.
<?php echo( rand( 1, 3 ) ); ?>
And Your Done
That’s all you should need, now if you save your file and upload it, you will see a random image display. To see what is being rendered simply view the source of the image link and you will see a static link with a hard coded image, which will change when you refresh the page.
This technique can be applied to more than just banners, you can use it on virtually anything. happy coding











Talk to me