9

We have a small php script, that displays random adverts on our site . The banners are served from any location we designate.

What I really would like to know, or be pointed in the right direction is, can we somehow collate the number of impressions each banner gets and possibly the click count on that banner.

I am sure this can be done in php, and stored in a db. Just havent got a clue. I searched on Google, and seemingly everything I could find harks back to 2002 and 2003 lol.

Here is our script:

<?php
$Img1 = "path to image folder/banner.png";
$Alt1 = "alt text for banner";
$Url1 = "http://www.externaldomain.com";

$Img2 ="path to image folder/banner.png";
$Alt2 = "alt text for banner";
$Url2 = "http://www.externaldomain.com";

$Img3 ="path to image folder/banner.png";
$Alt3 = "alt text for banner";
$Url3 = "http://www.externaldomain.com";

$Img4 ="path to image folder/banner.png";
$Alt4 = "alt text for banner";
$Url4 = "http://www.externaldomain.com";

$Img5 ="path to image folder/banner.png";
$Alt5 = "alt text for banner";
$Url5 = "http://www.externaldomain.com";

$num = rand (1,5);

$Image = ${'Img'.$num};
$Alt = ${'Alt' .$num};
$URL = ${'Url'.$num};

Print "<a href=\"".$URL."\"><img src=\"".$Image."\" alt=\"".$Alt."\" /</a>"; ?>

To initiate the above code ( we fire an include request )

<?php include ("../adserver/thescriptabove.php"); ?>
Zoe
  • 27,060
  • 21
  • 118
  • 148
422
  • 5,714
  • 23
  • 83
  • 139
  • Use [arrays](http://php.net/manual/en/language.types.array.php) instead of dynamic variables. – Czechnology Jan 31 '12 at 23:31
  • Could you explain more please, Im not very good with php – 422 Jan 31 '12 at 23:54
  • 1
    Sorry, I just meant that in this case using an associative array instead of dynamic variables might be better: `array(array('img' => 'image1.png', 'alt' => 'alt1', 'url' => 'url1'), array('img' => 'image2.png', 'alt' => 'alt2', 'url' => 'url2'), ...)`. Check the [_manual_](http://php.net/manual/en/language.types.array.php). – Czechnology Feb 01 '12 at 00:01
  • Thanks @Czechnology I will start learning php I think lol, its like double dutch to me. But seems to be the best way to fo, using arrays. Thankyou – 422 Feb 01 '12 at 00:26

5 Answers5

14

I see that you already selected an answer, so I'm not sure if you figured it all out, but I was writing out a little tutorial for you. Finally got it done, hope it still helps you out.

Your method seems to be working fine for serving banners, but if you're going to get into databases and tracking clicks/impressions, I would suggest that you go all in. So store your banner properties in the database as well. I'm going to get ahead and assume that your server/web host allows for a few free MySql databases.

What you need to do is create a database, as well as a User/Admin for the database. Then you're going to access the database with a MySql manager, most web hosts provide phpMyAdmin. Once you're inside the database, you need to set up a table to record your data.

Here's how I want you to set it up:

|Table Name: Banners      |
|-------------------------|
|Field:    | Type:        |
|-------------------------|
|ID        | int(5)       | The Primary Key and Autoincrement attributes should be set on the ID field as well
|Image     | varchar(100) |
|Url       | varchar(100) |
|Caption   | varchar(100) |
|Views     | int(10)      |
|Clicks    | int(10)      |

Now that you've got the database done, here comes the hard part, the PHP. I've pretty much done it for you, but it's untested, so I'm sure there will be bugs, that you will have to work out. But it should point you in the right direction, and help you learn.

<?PHP

// First of all, we need to connect to the MySql server
// For more info, check out: http://php.net/manual/en/function.mysql-select-db.php
$conn = mysql_connect("localhost", "username", "password");
if(!$conn){
    die('Could not connect to the MySql Server ' . mysql_error());
}

// Now that we've connected to the MySql sever, we need to select the database
// More info can be found on the same link as above
$db_selected = mysql_select_db('my_database', $conn);
if(!$db_selected) {
    die ('Could not select the MySql Database: ' . mysql_error());
}

// Now we need to check the URL parameters to see, if we came to this page normally or because a banner was clicked
// If normally, we serve a random banner and increment the Views field in the database
// Otherwise, we increment the Clicks field and direct the user to the banner's URL


if(!isset($_GET['Clicked'])){
    // if the Clicked parameter is not set, we came to the page normally

    // Let's select a random banner from the database
    $result = mysql_query("SELECT * FROM banners ORDER BY RAND() LIMIT 1") or die(mysql_error());
    $row = mysql_fetch_array(result);   

    // Now let's increment the Views field for the banner we selected
    mysql_query("UPDATE banners SET Views = Views + 1 WHERE ID = '" . $row['ID'] . "'") or die(mysql_error());

    // let's set the URL to this same page but with the Clicked parameter set
    $url = "banner_server.php?Clicked=" . $row['ID'];

    // Last but not least, we have to output the banner HTML
    // Notice, I set the caption on both the 'alt' and 'title' attributes of the 'img' tag,
    // that's because IE shows the value of the 'alt' tag when an image is hovered,
    // whereas Firefox shows the value of the 'title' tag, just thought you might want that!
    echo "<a href=\"" . $url . "\"><img src=\"" . $row['Image'] . "\" alt=\"" . $row['Caption'] . "\" title=\"" . $row['Caption'] . "\" /></a>";

}else{
    // Otherwise, increment the Clicks field and redirect

    // First, let's get the ID of the banner that was clicked from the Clicked parameter
    $id = (int)$_GET['Clicked'];

    // now let's increment the Clicks field for the banner
    mysql_query("UPDATE banners SET Clicks = Clicks + 1 WHERE ID = '" . $id . "'") or die(mysql_error());

    // now let's select the banner from the database so we can redirect to the URL that's associated with it
    $result = mysql_query("SELECT * FROM banners WHERE ID = '" . $id . "'") or die(mysql_error());
    $row = mysql_fetch_array(result);

    // redirect to the URL
    header("location: " . $row['Url']);
}


// Close the MySql connection
mysql_close($conn);

?>

Good luck

Saad Imran.
  • 4,480
  • 2
  • 23
  • 33
  • 1
    Aww apologies for that, i was on Tizag following some tuts. Will check out your code, happy to amend accepted anser. Cheers – 422 Feb 01 '12 at 00:51
  • So if I follow this correctly, we can just whack an include on the page and direct it to this php page and all is good. I like it – 422 Feb 01 '12 at 00:54
  • Ok nearly there. I keep getting error though ( I am connected to the database ) but when i run the php , this code appears..Warning: mysql_fetch_array() expects parameter 1 to be resource Also when adding a new record to database, i have to put in 0 into views and count otherwise it throws an error. Any suggestions please? – 422 Feb 01 '12 at 01:30
  • Hey Sorry, started watching T.V. Give me a sec – Saad Imran. Feb 01 '12 at 01:44
  • 1
    Thanksyou, seems to be $row = mysql_fetch_array(result); – 422 Feb 01 '12 at 01:46
  • @422 Sorry, figured it out. Mistake on my part, I accidentally left out the `$` sign. Made the error twice, `$row = mysql_fetch_array($result);` <-- That's the line, just add a `$` in front of `result` – Saad Imran. Feb 01 '12 at 01:47
  • Aww sweet. Seriously cool. I looked at result and thought.. him should be a string to parse the data lol. Ok now to make a front end , and some stats n shit. Cheers mate – 422 Feb 01 '12 at 01:51
  • The issue I see with this is not being able to aggregate views/clicks by time - which would be useful when pushing off this data over to a data warehouse for various analytical slicing/dicing. – J.D. Mar 29 '12 at 19:27
  • @JD. It's not meant to be an analytical software for distribution or anything, It's just a simple solution to original posters problem and to give him the basic idea, how he implements the rest is up to him. – Saad Imran. Mar 29 '12 at 19:53
6

why dont you just let google analytics do it for you? Fire off an event when the link is clicked and let google capture it?

onclick="_gaq.push(['_trackEvent', 'Event Name', 'click', 'Button title/name']);"
Philip
  • 4,592
  • 2
  • 20
  • 28
  • nah I want to keep it all in house. Thanks though good concept. – 422 Feb 01 '12 at 01:00
  • 1
    You can build your analytics into your admin dashboard http://code.google.com/apis/analytics/docs/gdata/home.html – Philip Feb 01 '12 at 01:04
  • Yer but I prefer if we can control everything, and do our own site analytics to spew out to advertisers. But never say never this could be a good option .. I am just to think to recognise it – 422 Feb 01 '12 at 01:08
  • 1
    You can add your client id to the event, then grab the metrics for that client, coupled with google charts http://code.google.com/apis/chart/ you can build their own client dashboard chart interface with their banner clicks etc. Good luck whatever you decide – Philip Feb 01 '12 at 01:23
  • My concern was displaying analytics for a particular user on our site, perhaps a combination of ga and Saad,s code may be just perfect. Still gotta make an admin interface to add records clientside too – 422 Feb 01 '12 at 01:37
1

Here are my 2 cents, assuming you have analytics on our site:

Use the following code when outputting a link:

<a class="ad" href="http://thecatisginger.com/" target="_blank" onclick="ga('send', 'event', 'Block-3-Ads', 'Click', 'The-Cat-Is-Ginger-Ad');"><img src="http://citybymouth.com/wp-content/uploads/2015/02/TCIG-Advert.jpg" onload="ga('send', 'event', 'Block-3-Ads', 'Impression', 'The-Cat-Is-Ginger-Ad', {'nonInteraction': 1});" /></a>

To explain:

<a class="ad" href="http://thecatisginger.com/" target="_blank"

Classic link a href link with class 'ad', links to a site, target opens in new tab. Easy.

onclick="ga('send', 'event', 'Block-3-Ads', 'Click', 'The-Cat-Is-Ginger-Ad');">

This is the newer 'analytics.js' google event tracking, onclick event code, that bascially says, hey, you've clicked this link, so 'send' this 'event' to my analytics 'Events' (which can be checked under "Realtime > Events" or "Behaviour > Events"). "Block-3-Ads" is the area on my website I personally know as the area I put ads, specifically its a right hand sidebar area, but it can be anything you want, so make yours a broad category type thing, like a box, inside which you will have different links you want to track. "Click" is simply the type of event you want to track, can be anything. "The-Cat-Is-Ginger-Ad" is this specific ad I want to track and have the information about.

<img src="http://citybymouth.com/wp-content/uploads/2015/02/TCIG-Advert.jpg" 

Then you have an img with a src. Easy.

onload="ga('send', 'event', 'Block-3-Ads', 'Impression', 'The-Cat-Is-Ginger-Ad', {'nonInteraction': 1});" />

Then you have an onload event that fires when the image is loaded, it says, 'send' this 'event', categorise it as a 'Block-3-Ads' event, basically the image loading is counted as an 'Impression', before it was click, but not since this little 'onload' is called when it loads, its not a click, but a load / impression, and again, specifically, the ad loaded is 'The-Cat-Is-Ginger-Ad', and finally, there is passing the 'nonInteraction' parameter as 1, which is just telling google you are tracking a non interaction event.

Its pretty self explanatory, tho I may have typed too much.

WARNING: This is not perfect in that the page may load, and the ad may be below the viewport, out of sight of the user, and still get an impression, which is not accurate, so next I'll be working on firing the impression code just once when the user actually scrolls to the ad itself, and views it, instead of firing it every time a page loads that image.

Bernard Myburgh
  • 169
  • 1
  • 2
1

You can store the $num in the database pretty easy to get your impression count. Clicks require client side action. The easiest way is to call a javascript function that counts when the banner is clicked via AJAX:

print "<a href=\"".$URL."\" onclick=\"countClick($num);\"><img src=\"".$Image."\" alt=\"".$Alt."\" /</a>";

Then have your javascript function (countClick()) execute the AJAX that will tell the server the banner has been clicked.

Another way is to have a passthru page: mysite.com/linkout.php?q=www.google.com and then have linkout.php count that link and update the database, and then redirect them to the variable passed in the URL.

Tim Withers
  • 12,072
  • 5
  • 43
  • 67
0

Thanks to @Saad Imran for the code and also big thanks to the question poster

Bellow the update of the code in php 7 if someone else need it for later use

Note : The same Database table and then store this code in banner.php file

<?php
    // to only count views

    // select a random banner from the database to show
    $rows = $db->QueryFetchArrayAll("SELECT * FROM banners ORDER BY RAND() LIMIT 1");
foreach ($rows as $row) {

    // Now let's increment the Views field for the banner we selected

    $url = "/banner.php?clicked=" . $row['ID'];

    echo "<a href=\"" . $url . "\"><img src=\"" . $row['Image'] . "\" alt=\"" . $row['Caption'] . "\" title=\"" . $row['Caption'] . "\" /></a>";
}
    $db->Query("UPDATE banners SET Views = '".round($row['Views'] + 1)."' WHERE id = '" . $row['ID'] . "'");

// to count clicks need an if statement 
if(isset($_GET['clicked'])){
        $db->Query("UPDATE banners SET Clicks = '".round($row['Clicks'] + 1)."' WHERE id = '" . $row['ID'] . "'");

header("location: " . $row['Url']);


}
?>

Good luck everyone :)

Khaled D
  • 1
  • 2