Tech-Evangelist

Technical Articles, Musings and Opinions from Tech-Evangelist

  • Home
  • About
  • Guidelines
Previous article: Mozilla Thunderbird Tips and FAQs
Next article: View Source is Not Working in Internet Explorer

Simple PHP Banner Ad Rotator Script

August 3, 2007 By Jonathan - Copyright - All Rights Reserved

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. 😀

Filed Under: PHP Tutorials, Web Site Development

Comments

  1. Steve says

    September 26, 2007 at 8:13 pm

    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!

  2. Danish says

    October 3, 2007 at 12:07 pm

    This Article/Material of Ad Rotator was proved very good to me.Thanks a lot.

  3. Mrs. VJ says

    October 20, 2007 at 8:39 pm

    Finally, a script that works! Thanks for the heads-up on this snippet of code!

  4. Roger in Jamaica says

    December 12, 2007 at 5:55 pm

    This script is the easiest thing since sliced bread. I wonder why the other option have to be so complicated. Thanks a million.

  5. Jenice a struggling webmaster says

    December 29, 2007 at 1:53 am

    Thank you for providing this script. I have been struggling for several days with this and your script did the job so simply. Thanks!

  6. Kai a panic 14 year old says

    January 22, 2008 at 5:26 pm

    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.

  7. Lana says

    February 2, 2008 at 4:05 am

    You saved my life. Thanks a billion for this!

    Oh it will be so satisfying to delete that horrid Javascript rotator I have now…

  8. Brett says

    February 29, 2008 at 12:47 pm

    I need to find a script that will automatically rotate the picture every so many seconds.

  9. TE says

    March 1, 2008 at 5:35 pm

    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.

  10. Mihai says

    March 2, 2008 at 1:18 pm

    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 ?

  11. TE says

    March 5, 2008 at 5:01 pm

    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.

  12. Danita says

    March 20, 2008 at 1:07 pm

    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?

  13. TE says

    March 21, 2008 at 6:43 pm

    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].

  14. Fabian says

    March 26, 2008 at 10:48 am

    The banners are rotated in random order, how can I do to rotate the banners in “not random” order?
    Thank you!

  15. TE says

    March 26, 2008 at 1:34 pm

    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.

  16. Danita says

    March 26, 2008 at 9:12 pm

    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.

  17. TE says

    March 27, 2008 at 8:34 am

    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.

  18. Owen says

    April 2, 2008 at 1:37 pm

    Hi. What if I wanted this to be consecutive instead of random?

  19. TE says

    April 3, 2008 at 8:01 am

    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.

  20. paddy m says

    June 16, 2008 at 6:49 am

    A neat and elegant solution for a php illiterate like me!

  21. Akshaye says

    June 22, 2008 at 9:17 am

    Hi
    Can this script work with swf files or only gif format?

    Thank u.

    Rgds
    Aks

  22. TE says

    June 23, 2008 at 5:21 am

    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. 🙂

  23. THIS WORKS TOO says

    September 15, 2008 at 7:59 am

    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]);
    };

  24. TE says

    September 16, 2008 at 7:06 am

    That is basically the same thing using JavaScript rather than PHP.

  25. Nuno Santos says

    November 7, 2008 at 3:19 am

    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!

  26. Doogie says

    November 9, 2008 at 10:56 am

    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.

  27. Dave says

    January 26, 2009 at 12:19 pm

    Thanks a lot, works great!

  28. PPC Tracking says

    February 17, 2009 at 6:37 pm

    This was one of the most effective and SIMPLE scripts I have ever come across! It does exactly what I needed – thanks so much!

  29. enow Mbi says

    February 20, 2009 at 5:11 am

    Thanks for the code. Looks so simple yet saves a great deal of stress.Thanks

  30. Joe says

    February 25, 2009 at 9:04 am

    How would I display two ads at a time using thing but stop it from displaying the same ad twice?

  31. Doogie says

    February 26, 2009 at 7:26 am

    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.

  32. Engineer says

    March 6, 2009 at 11:23 am

    This is a wonderful code. You can even include a google script to run in conjunction with the regular ads.
    Absolutely wonderful.
    Thank you.

  33. EV says

    April 30, 2009 at 11:09 am

    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!

  34. Doogie says

    May 1, 2009 at 8:18 am

    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.

  35. sharedrecipesdotorg says

    May 30, 2009 at 4:20 am

    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.

  36. needmusic says

    June 14, 2009 at 5:02 pm

    Thanks for this script . It works perfect.
    I wonder if it`s possible to rotate background images???

  37. spirosMR says

    November 11, 2009 at 7:58 am

    Hello guys. I want to ask if I can track every click on each ad with this script. Thank you in advance.

  38. Doogie says

    November 13, 2009 at 2:34 pm

    There is no tracking with this script.

  39. ncube digital says

    December 7, 2009 at 11:00 am

    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.

  40. Distractedthinking says

    January 27, 2010 at 4:08 am

    cool script, it is working cool with jpg and swf… thanks a lot

  41. Dave says

    December 5, 2010 at 4:43 am

    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.

  42. Michael R says

    December 30, 2010 at 9:35 pm

    Excellent script! Very helpful, indeed…

  43. Joe says

    April 26, 2011 at 1:24 pm

    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.

  44. dariel says

    August 18, 2011 at 3:49 pm

    That Simple script but powerfull.
    Thanks for sharing this scripts this scripts work with every way. swf, images, event adsenses.
    great scripts

  45. Accountant List says

    October 13, 2011 at 7:58 am

    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!!

  46. Ang says

    January 25, 2012 at 5:41 am

    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!

  47. Doogie says

    January 29, 2012 at 12:09 pm

    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.

Categories

  • Affiliate Marketing
  • CSS Tutorials
  • FileZilla Tutorials
  • Home Theater
  • Internet Marketing
  • Internet Technology
  • Kindle Tips
  • MySQL Tutorials
  • Online Auction Tips
  • Paint Shop Pro Tutorials
  • PHP Tutorials
  • Tech News
  • Thunderbird Tutorials
  • Video Production
  • Web Site Development
  • WordPress Tutorials
follow me on Twitter
Content and images are copyrighted by Tech-Evangelist.com and others

Copyright © 2022 Tech-Evangelist.com - All Rights Reserved
Posted code samples are free to use. Do not reproduce or republish articles or content on another web site.

Privacy Policy : Terms of Use