Be a Supporter!

Creating A Random Ad

  • 3,694 Views
  • 9 Replies
New Topic Respond to this Topic
Jams44
Jams44
  • Member since: Nov. 8, 2004
  • Offline.
Forum Stats
Member
Level 07
Blank Slate
Creating A Random Ad Dec. 15th, 2005 @ 07:55 AM Reply

PHP: Main

Creating a PHP Random Ad Script

After many tutorials have been with randomosity as their key point, why not one
that could actually be useful?

In this tutorial I will show you the steps frm beginning to end (with explination) on how
to create your own random ad manager.

First of we will start with most obvious starting point- The opening PHP tag

<?

Next we will define what are ads are and their location

$ads = array("http://site.com/image1.gif", "http://site.com/image2.gif", "http://site.com/image3.gif"); ///Since their are multiple ads we will use the array function

Next we will define the links that will go with each of the ads. REMEMBER the links must be in the same order as their ad images!

$links = array("http://link1.com", "http://link2.com", "http://link3.com");

Now to the harder stuff, we must take a direct count of the number of ads, so we will use the count function

$total_ads = count($ads);

And now we must have the ads randomly picked

$pick_ad = rand(0, $total_ads-1);

Finally we must echo our results to be displayed on your page

echo '<img src="' . $ads[$pick_ad] . '">';

Followed by the closing PHP tag

?>

The whole script combined-

<?
$ads = array("http://site.com/image1.gif", "http://site.com/image2.gif", "http://site.com/image3.gif");
$links = array("http://link1.com", "http://link2.com", "http://link3.com");

$total_ads = count($ads);

$pick_ad = rand(0, $total_ads-1);

echo '<img src="' . $ads[$pick_ad] . '">';
?>

This script is rather short and simple but is very nice when you have affiliates you want to show.
This tutorial is meant for PHP: Main and was brought to you by Jams44

henke37
henke37
  • Member since: Sep. 10, 2004
  • Offline.
Forum Stats
Member
Level 30
Blank Slate
Response to Creating A Random Ad Dec. 15th, 2005 @ 12:53 PM Reply

You are forgeting the most important part, geting to know when a ad is clicked, so you can charge for it. While small sites proably won't need it, you should mention it.
I got a solution for that, make a page with the following code. It uses a mysql database. Make all ad images link to it(the <a> part) like this; "adlog.php?ad=$adid".
<?php//called adlog.php
//notice that since this page sets a header, no blankspace is allowed before the starttag nor in or affter the tag in any includes. Output buffering will fix the error, but that's bad practise.
$adid=(int)$_GET["ad"];//Type cast to stop bad data

$refer=$_SERVER['HTTP_REFER'];

require 'dbpassword.php';//never put it in hardcoded

@$db_con=mysql_connect(DB_HOST,DB_USER,DB_
PASS);//consts from 'dbpassword.php'
if(!$db_con or @!mysql_select_db(DB_NAME)) {
header('Location: http://yoururl/errorpage.html');
die();
}

//prepare the database query
$sql ='select afflies.url,afflies.id as afflieid from ads join afflies on ads.afflie=afflies.id';
$sql.=' where ads.id='.$adid;

$adres=@mysql_query($sql,$db_con);

if(!$adres) {
header('Location: http://yoururl/errorpage.html');
die();
}

$url=mysql_result($adres,0,'url');//read data from the query
$afflieid=mysql_result($adres,0,'afflieid'
);

//now redirect the clicker to the url
header('location: '.$url);

//update the database
$sql ='insert into adclicks (adid,refer) ';
$sql.='values('.$adid.',\''.mysql_real_esc
ape($refer,$db_con).'\')';
//notice that the refer is NOT safe and needs to be escaped

$upres=@mysql_query($sql,$db_con);
if(!$upres) {
//your choice if it should go to the error page or not
}
?>

And for completnes a function to get a random ad for display:
<?php
function displayrandomad() {
global $db_con;//this function doesn't handle connection to the db

$refer=$_SERVER['HTTP_REFER'];

if(!$db_con) {
throw new Exception('check the dam db con!');//php5 only feature
return false;//use this for php4
}

$sql='select id,type from ads order by random limit 1';
//can be more complex if you want targeted ads
//notice the limit 1 that makes sure the script only get 1 ad
// and doesn't waste bandwith(bethwen server and database)

$adres=@mysql_query($sql,$db_con);

if(!$adres or mysql_count_rows($adres)<1) {
throw new Exception('check the dam db query!');//php5 only feature
return false;//use this for php4
}

$adid=mysql_result($adres,0,'id');
$adtype=mysql_result($adres,0,'type');

$sql ='insert into adviews(adid,refer)';
$sql.=' values('.$adid.',\''.mysql_real_escape($re
fer,$db_con).')';

$upres=@mysql_query($sql,$db_con);

if(!$upres) {
throw new Exception('check the dam db query!');//php5 only feature
return false;//use this for php4
}

//notice that < and > are replaced with [ and ] to pass thrugth the forum
if('swf'==$adtype) {//flash needs different html
//put the proper html for flash here
} else {
printf('[a href="adlog.php?ad=%1$s"][img src="ads/%1$s.%2$s" border="0"][/a]',$adid,$adtype);
}
}


Each time someone abuses hittest, God kills a kitten. Please, learn real collision testing.

Jams44
Jams44
  • Member since: Nov. 8, 2004
  • Offline.
Forum Stats
Member
Level 07
Blank Slate
Response to Creating A Random Ad Dec. 15th, 2005 @ 06:54 PM Reply

Hey, how about posting your tutorial in the PHP Main, then at the beginning you can say its an addition to this, trhat way we both get credit!

Greeley
Greeley
  • Member since: Aug. 30, 2005
  • Offline.
Forum Stats
Member
Level 13
Blank Slate
Response to Creating A Random Ad Dec. 17th, 2005 @ 08:33 PM Reply

Good job guys. I already had a random ad manager made. I'm thinking of recoding it and making it abit better one of these days though. I find it easier to do arrays like this though:

$image[] = 'image1.gif';
$image[] = 'image2.gif';

$link[] = 'link1.com';
$link[] = 'link2.com';

Not like it really matters but it's just an alternative for those of you who didn't know that which I'm sure most of you did.

Craige
Craige
  • Member since: Jul. 17, 2004
  • Offline.
Forum Stats
Member
Level 08
Blank Slate
Response to Creating A Random Ad Dec. 17th, 2005 @ 09:05 PM Reply

At 12/17/05 08:33 PM, Greeley wrote: I find it easier to do arrays like this though:

$image[] = 'image1.gif';
$image[] = 'image2.gif';

$link[] = 'link1.com';
$link[] = 'link2.com';

I only recomend that method if you are only adding 1 value to an array at a certain point. It get's kinda messy if you are adding more than one value at a time. It is allot cleaner, and easier, at that point, to just do it like showed above.

Greeley
Greeley
  • Member since: Aug. 30, 2005
  • Offline.
Forum Stats
Member
Level 13
Blank Slate
Response to Creating A Random Ad Dec. 19th, 2005 @ 09:33 PM Reply

At 12/17/05 09:05 PM, Dezmerkt wrote:
At 12/17/05 08:33 PM, Greeley wrote: I find it easier to do arrays like this though:

$image[] = 'image1.gif';
$image[] = 'image2.gif';

$link[] = 'link1.com';
$link[] = 'link2.com';
I only recomend that method if you are only adding 1 value to an array at a certain point. It get's kinda messy if you are adding more than one value at a time. It is allot cleaner, and easier, at that point, to just do it like showed above.

Meh... in my opinion it is easier and keeps things neat and tidy. It helps me keep track of the links that correspond to the ads. But that's just my opinion. It really all depends on the persons coding style.

WoogieNoogie
WoogieNoogie
  • Member since: Jun. 26, 2005
  • Offline.
Forum Stats
Supporter
Level 15
Programmer
Response to Creating A Random Ad Dec. 19th, 2005 @ 09:45 PM Reply

There's also a Javascript way of doing this...

<SCRIPT TYPE="text/javascript">
<!--Putting in the array for the variable, just the HTML-->
var Randomness = new Array("<A HREF='http://site1.com'><IMG SRC='pic1.jpg'>","<A HREF='http://site2.com'><IMG SRC='pic2.jpg'>");
<!--Making the random math...nice and notnice :)-->
var notnice = Math.random()*Randomness.length-1;
var nice= Math.abs(Math.round(notnice));
<!--Write it out-->
document.write(Randomness[nice]);
</SCRIPT>

I know this is a PHP thread...but I couldn't help myself...

DannyIsOnFire
DannyIsOnFire
  • Member since: Apr. 14, 2005
  • Offline.
Forum Stats
Member
Level 21
Movie Buff
Response to Creating A Random Ad Feb. 21st, 2006 @ 03:11 PM Reply

Question, about the original script.
Is there a way to make the links open in a new wondow... i tried adding the usual target=_blank but it isnt working.
Thanks.


|| Portfolio || Facebook || Twitter ||

BBS Signature
henke37
henke37
  • Member since: Sep. 10, 2004
  • Offline.
Forum Stats
Member
Level 30
Blank Slate
Response to Creating A Random Ad Feb. 22nd, 2006 @ 09:51 AM Reply

If you 'd know html you would have seen that the orginal script didn't even make the image clickable.


Each time someone abuses hittest, God kills a kitten. Please, learn real collision testing.

phyconinja
phyconinja
  • Member since: Sep. 18, 2004
  • Offline.
Forum Stats
Member
Level 25
Blank Slate
Response to Creating A Random Ad Oct. 21st, 2006 @ 07:38 PM Reply

would it be posible to do like:

<?
$ads = array("http://site.com/image1.gif", "http://site.com/image2.gif", "http://site.com/image3.gif");
$links = array("http://link1.com", "http://link2.com", "http://link3.com");

echo '<img src="' . $ads[rand(0, count($ads)-1);] . '">';
?>

??
insted of the code to the topic starter.. cuz this would be shorter if the code is rely long!