Banner ad rotators can range in complexity from simple systems that randomly display banner or sidebar ads, to very complex systems that track every click on each ad and display different ads based upon preset percentages for each ad display.
This snippet of PHP code is the simple version. As many ads as you want can be loaded into an array and the code will randomly select an ad to display every time the page is loaded. This is a good solution for someone who wants to randomly display either advertising links or images on a page. It works well with banner image links found with many banner exchange programs and affiliate marketing programs. Simply substitute the code provided by your affiliate network or advertising partners for the value part of the name-value pairs in the following code.
Here is the code for the simple PHP banner ad rotator:
<?php $bannerAd[1] = 'code for ad 1'; $bannerAd[2] = 'code for ad 2'; $bannerAd[3] = 'code for ad 3'; $bannerAd[4] = 'code for ad 4'; $bannerAd[5] = 'code for ad 5'; $adCount = count($bannerAd); $randomAdNumber = mt_rand(1, $adCount); echo $bannerAd[$randomAdNumber]; ?>
Here’s how it works:
HTML or JavaScript code is loaded as a single line within a cell in the numeric array. $adCount determines the number of elements in the array. The array must start with an element numbered as 1, but can contain as many elements as you want. Don’t leave any gaps in the numbering sequence. A random number is generated from 1 to the $adCount value and stored in $randonAdNumber, which then displays the banner ad code for that designated cell in the array. All you need to do is to cut and paste the code into a Web page on a PHP enabled server and substitute your ad code in the array.
Either HTML or JavaScript code can be loaded into each cell of the array. Double quotes used with attribute values do not present a problem, but single quotes sometimes do cause problems. Note that single quotes are used to delimit the contents of a cell. If you run into PHP errors related to the array, look for single quote characters that may be causing a problem. You can either eliminate them or convert them to double quotes.
The following is an example of the hyperlink code for an advertising link. The code should be on a single line in your script.
$bannerAd[1] = '<a href="http://www.tech-evangelist.com/" target="_blank"><img src="/images/banner01.gif" width="468" height="60" border="0"></a>';
If you want to use this script to randomly display images, just eliminate the hyperlink code and use the image portion of the code like the following.
$bannerAd[1] = '<img src="/images/banner01.gif" width="468" height="60" border="0">';
Remember to place this on a single line in your script. 😀
Steve says
Hi folks- Just a note of thanks for the great code on banner rotation… This was exactly what I was looking for. After spending too much time with javascript rotators, etc… your php solution is perfect. Best regards!
Danish says
This Article/Material of Ad Rotator was proved very good to me.Thanks a lot.
Mrs. VJ says
Finally, a script that works! Thanks for the heads-up on this snippet of code!
Roger in Jamaica says
This script is the easiest thing since sliced bread. I wonder why the other option have to be so complicated. Thanks a million.
Jenice a struggling webmaster says
Thank you for providing this script. I have been struggling for several days with this and your script did the job so simply. Thanks!
Kai a panic 14 year old says
For a few weeks I’ve been trying to make a ‘Did you know’ box on my game.
I had tryed all sorts but they didn’t comply with the rest of my scripts whic annoyed me.
Now this is perfect sits there and looks great
Thanks a lot guys.
Lana says
You saved my life. Thanks a billion for this!
Oh it will be so satisfying to delete that horrid Javascript rotator I have now…
Brett says
I need to find a script that will automatically rotate the picture every so many seconds.
TE says
Hi Brett
You will need to use either a JavaScript routine, or Adobe Flash, or an animated GIF to automatically rotate images. A PHP script executes on the server (it is server-side code) and cannot rotate images in a user’s browser. You will need to use client-side code, which is code that executes in a user’s browser.
Mihai says
Where do I have to put “$bannerAd[1] = ‘‘;” ? In the html file or do I have to make a file with .php extension and make a link to it in the html page ? I want to make simple websites for my customers which I’ll host for free on my account. In exchange I want to put a banner in top of the index.html page; your script can do that ?
TE says
Hi Mihai
You cannot run PHP in a standard HTML file. PHP code must be run through a PHP parser. The PHP code needs to be executed by the server before the page is sent to the user’s browser. That means you either have to use a .php extension on a server that runs PHP or you can force the server to run all HTML code through the parser by modifying the .htaccess file. Standard HTML files are sent directly to the user’s browser and no code is executed on the server.
If your site can run PHP, all you need to do is cut-and-paste the entire block of code into your page script wherever you want it to display on the page. Then you insert your image hyperlinks. You should probably learn some basic PHP before you tackle this.
Danita says
I love this! Is it possible to use it in more than one place on the page?
I’ve tried renaming $bannerAd to $bannerAdCube and $adCountCube and $randomAdNumberCube so ti wouldn’t interfere, but no dice. I breaks. It shows all 5 ads with the code between.
Any suggestions?
TE says
You can use it exactly as it is multiple times on a page and just change the ad or image values assigned to the array, as long as each array contains the same number of elements. Each block of banner ad code will run separately because values are reassigned.
If it broke it was probably because you did not change all the incidents of a variable name within the code block. You need to change the variable names in the array, as well. Also, make sure that there aren’t any breaks in the numeric sequence of your array assignments. For example, you cannot skip $bannerAd[3] in the above example. Start with $bannerAd[1] and add as many array elements as you wish.
If you are going to run it multiple times on a page it would be better to change each incident of $bannerAd to a unique variable name for each banner ad code block. In other words, use $bannerAd1 for the first code bloc, $bannerAd2 for the second, etc. Otherwise, you could run into issues if you assigned five array elements to the first ad block, but only three to the second. if you do not change the variable names to something unique, the second ad block would still see values $bannerAd[4] and $bannerAd[5].
Fabian says
The banners are rotated in random order, how can I do to rotate the banners in “not random” order?
Thank you!
TE says
Hi Fabian
You cannot rotate banners images in order with a just a PHP script like this one that runs on a server. You need some way to keep track of a count and then increment the count to display another ad. A PHP script cannot do that internally because it is no longer running when the page is sent to the user’s browser.
You could do something with PHP using a session or a cookie to keep track of a count and then read the count and increment it every time a page displays.
If you need to automatically change an ad or an image in a particular sequence without reloading the page, then look for solutions that run in a browser, such as Flash, JavaScript or an animated GIF.
Danita says
Hi!
I edited the code as you recommended and as shown below:
<?php
$bannerAdCube[1] = ‘code for ad 1’;
$bannerAdCube[2] = ‘code for ad 2’;
$bannerAdCube[3] = ‘code for ad 3’;
$bannerAdCube[4] = ‘code for ad 4’;
$bannerAdCube[5] = ‘code for ad 5’;
$adCountCube = count($bannerAdCube);
$randomAdNumberCube = mt_rand(1, $adCountCube);
echo $bannerAdCube[$randomAdNumberCube];
?>
If you take a look at veganworldezine.com you will see that I’ve used it at the top of the page above the header and it works perfect, but my problem is in trying to use it a second time at the bottom of the left column. The ad still shows with all 5 images and code – on a Mac running Firefox. On a Windows machine, the ad does not show up at all.
Is there something wrong in the way I edited the code? Or is there another workaround? Any help is very much appreciated.
TE says
Hi Danita
The PHP code for the second set of ads is being sent to the browser and displays in the code, which means it is not being executed properly on the server.
Also, the PHP require_once code for the first code block is displaying when you list the page code via View, Source.
PHP code should never display in the client-side code sent to the browser. If it is displaying, it is not being parsed properly.
Let’s take it one problem at a time. The first block of PHP code is being included in the HEAD section of the page. This code, and any code to display something on a page, must be executed within the BODY tags, not in the HEAD section. If you want a banner ad to display at the top of the page, the PHP code must be inserted just after the opening BODY tag.
Try fixing that and let us know if it fixes the problem.
The difference between the way the browsers display the ads it very likely just the difference in the way that they handle client-side code that is not HTML or JavaScript.
This may not be the root of the problem, because if the first block of code was being parsed properly on the server, it should just display the HTML code for a single banner ad in the client-side code, and not the PHP code.
It looks like you are using fully formed URLs to include your banner ad files. These URLs should be relative to the current directory that the main file is called from. Try changing the require_once include statement to a format like this:
include(‘Ads/microADRotator.php’);
This takes a few other PHP issues out of the equation.
Let us know what happens.
Owen says
Hi. What if I wanted this to be consecutive instead of random?
TE says
Hi Owen
Read my response to Fabian. You cannot do this using only PHP because you will need to store a counter value. The easiest way to store a counter is by using a session or a cookie.
Check back in a few days. As soon as I get some time I will wriite a version that uses a session or cookie counter.
paddy m says
A neat and elegant solution for a php illiterate like me!
Akshaye says
Hi
Can this script work with swf files or only gif format?
Thank u.
Rgds
Aks
TE says
Hi Akshaye
As shown above the scritpt can work with any web image format, .gif, .jpg or .png. It could be modified to use JavaScript calls to randomly display flash files embedded in JavaScript functions.
I’ll put that on my list of articles to write. 🙂
THIS WORKS TOO says
Your script is cool. I got this one and it works well too.
function banner() {
banner = new banner();
number = 0;
// bannerArray
banner[number++] = “<a href='YOUR URL HERE' rel=”nofollow”></a>”;
banner[number++] = “<a href='YOUR URL HERE' rel=”nofollow”></a>”;
banner[number++] = “<a href='YOUR URL HERE' rel=”nofollow”></a>”;
// keep adding items here…
increment = Math.floor(Math.random() * number);
document.write(banner[increment]);
};
TE says
That is basically the same thing using JavaScript rather than PHP.
Nuno Santos says
I have this script running on my site but now I have one question.
If I place the same script (which is runing with 10 different ads) on another php page and have the same 10 ads runing is there a way for the new php page when it loads to keep loading ads from where the last ad was loaded.
I mean like this its like returning to the beginning every time a new php page loads.
not sure if i’m explaining correctly!
Doogie says
Hi Nuno
I think I understand. Let me know if I do not.
This script will not do that. Each page runs independently. Besides that, the script does not run ads consecutively; it runs them randomly. It is possible to have the same ad display 2 or 3 times in a row.
If you want to run ads in a particular order that is independent of the page a user is viewing, you have to keep track of a count and increment it. You could do that using a cookie or with sessions. Every time they load a page, read the cookie, increment the count and then display the ad related to that particular number.
Dave says
Thanks a lot, works great!
PPC Tracking says
This was one of the most effective and SIMPLE scripts I have ever come across! It does exactly what I needed – thanks so much!
enow Mbi says
Thanks for the code. Looks so simple yet saves a great deal of stress.Thanks
Joe says
How would I display two ads at a time using thing but stop it from displaying the same ad twice?
Doogie says
Hi Joe
I assume that you want to set up two separate ad blocks in different locations on a web page. If that is correct, then the easiest solution would be to use the same PHP routine twice on the page, but include different ads in each group. That is the best way to assure that the same ad does not display in the two locations at the same time.
Engineer says
This is a wonderful code. You can even include a google script to run in conjunction with the regular ads.
Absolutely wonderful.
Thank you.
EV says
Hi – great script! Wondering how many images are allowed in an ad block using this script? Can you have only single digits 1-9 or can you go beyond this? Thanks for posting such a CLEAN useful script!
Doogie says
Hi EV
You can have as many images and code blocks as you want. There is no limit. Just make sure that your array is numbered sequentially with no number gaps.
sharedrecipesdotorg says
wow, i just had to take the time to leave a message of a HUGE thanks for this. i have been hunting around for this exact thing for awhile now, and not to rotate banners. this script worked so i could rotate videos on my site. i have around 40,000 pages and the way my script works i could only add a single code for all pages to share, this little php code makes it so visitors hunting around on my site will get some new stuff to watch with each page. all i did was enter the codes for the video embeds where the “banner” codes would go and it works perfect! thank you so much! i cant wait to add dozens more 🙂 man, this would of come in handy on the sites i used to have.
needmusic says
Thanks for this script . It works perfect.
I wonder if it`s possible to rotate background images???
spirosMR says
Hello guys. I want to ask if I can track every click on each ad with this script. Thank you in advance.
Doogie says
There is no tracking with this script.
ncube digital says
I am in the process of building a website and wanted a database driven php random banner rotator. this served a good purpose so i thought i would publish a simple addition in order to make it database driven. hopefully this will help anyone who wants to build on this nice snippet from TE.
php script is as follows;
//include database connection details
include(“includes/connect.php”);
mysql_connect($dbhost, $dblogin, $dbpass);
@mysql_select_db($db) or die(‘Could not select db’);
$result = mysql_query(“SELECT * FROM test”) or die(0);
while ($row = mysql_fetch_array($result)){
$bannerAd[] = $row[‘bannerimg’];
}
$adCount = count($bannerAd)-1;
//the -1 here serves to avoid a blank image. in my test the db had 3 records, the script sees 3 within the array but as the array starts from 0 the value of 3 in the array creates a blank image.
$randomAdNumber = mt_rand(0, $adCount);
//the 0 rather than 1 here is similar to the above so that the first record in the db shows up. if this is set as 1 then it will not read the 0 (first) value in the array
echo $bannerAd[$randomAdNumber];
The code blocks are contained within the db records.
I’ll check back here every few days incase of any questions.
Distractedthinking says
cool script, it is working cool with jpg and swf… thanks a lot
Dave says
EXCELLENT and SIMPLE script!!! almost too easy. 🙂 Much easier than the others I have been playing with. I have it rotating both images and flash files with no problems at all.
Thank you.
Michael R says
Excellent script! Very helpful, indeed…
Joe says
I’m using this script to display text. If you need to use single quotes in your text, for example as apostrophes, you can “escape” them by putting a \ right in front of them. Like this: Mom\’s homemade pie.
dariel says
That Simple script but powerfull.
Thanks for sharing this scripts this scripts work with every way. swf, images, event adsenses.
great scripts
Accountant List says
This was exactly what I was looking for to rotate ads on a site with a huge number of pages. Having the same ad in the same spot on every page loses its effectiveness. Thank you!!
Ang says
I’ve been using this for a few years and it works SUPER! I’d now like the right 250×250 banners and the left 120×600 banners to rotate together and match.
Any suggestions for how to change the random function to loop through 1,2,3,4,etc as I have a separate php page for each one is the sidebar.php and the other single.php
Thanks!
Doogie says
Hi Ang
You could set up two arrays and modify the code so that a pair of ads displays together each time.
Example:
$bannerAd1[1] = ‘code for ad 1 for banner 1’;
$bannerAd2[1] = ‘code for ad 1 for banner 2’;
You cannot force it to loop through a series of ads in a sequential order unless you use a database or some way to keep track of a number that is incremented as each ad is displayed. That would be cumbersome.
It may be possible to do this with a cookie so that a user picks up the cookie and sees the first ad, then when the next page is loaded the number is incremented and they see the second ad and so on. When they reach the last array element the number would have to be reset to 1. That should work.