Login

My PHP Digest

Random banner rotation

20th May 2007

This is a very simple thing to do, which can get you some money the 2 examples below are straight forward. The first being the easiest to do with a simple echo output, the next does a echo output as well as log the amount of times the banner has been shown

Example 1

Add a directory called banners, then add your banner images, in this example I will use 2 images, use numbers for them, so I will have the following image names in my banners folder

  • 1.png
  • 2.png

then just add this to any page to show the banners


<?php
    
echo 'http://www.example.com/banners/'.rand(12).'.png';
?>

rand(1, 2); means that it will randomize thought 1 and 2, so if I made it, rand(1, 5); it''' randomize thought 1 to 5.

Example 2

Create the SQL table

CREATE TABLE `phpidiots`.`statistics` ( `ID` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, `Date` DATE NOT NULL DEFAULT '0000-00-00', `IPAddress` VARCHAR(12) NOT NULL DEFAULT '', `AID` INTEGER UNSIGNED NOT NULL DEFAULT 0, PRIMARY KEY(`ID`) ) ENGINE = InnoDB;

Now create the file example.php and add the code below


<?php
    
    
if(empty($_GET["id"])){
    
        
// We need to put the random number into a thingy
        
$id rand(12);
        
        
// Display the advert
        
echo '<a href="example.php?id='.$id.'">http://www.example.com/banners/'.$id.'.png</a>';
    } else {
    
        
// _GET must be Integer only!!
        
if(is_numeric($_GET["id"])==FALSE) die('Hack Attempt');
        
        
// Connect to MYSQL
        
$md mysqli_connect('127.0.0.1','root','','phpidiots');
        
        
// Insert the information we need
        
mysqli_query($md,"INSERT INTO statistics (Date, IPAddress, AID) VALUES ('".date('Y-m-d')."', '".$_SERVER['REMOTE_ADDR']."', '".$_GET["id"]."')");
        
        
// Be efficent!
        
mysqli_close($md);
        
    if(
$_GET["id"]==1){
        
$loc 'http://advert1-site.com';
    } elseif(
$_GET["id"]==2){
        
$loc 'http://advert1-site.com';
    }

        
// Redirect to the webpage now
        
header('Location: '.$loc);
    }

?>

then just add a include('example.php'); to any page from which it'll show the banner and when it's clicked it'll record your hits! Then from using cleaver SQL query's you can show how many hits they get per day, week, month or year.

© 2006 John's PHP Digest. All Rights Reserved