21.8 Choosing Banner Ads
Another use for random numbers is selecting banner ads. Suppose you've signed up three sponsors for your Web site. Each has a single banner you promise to display on an equal proportion of hits to your site. To accomplish this, generate a random number and match each number to a particular banner. In Listing 21.10, I've used a switch statement on a call to mt_rand. In a situation like this, you don't need to worry too much about using good seeds. You simply want a reasonable distribution of the three choices. Someone guessing which banner will display at midnight poses no security risk.
Listing 21.10 Random banner ad
<?php
//Seed the generator
mt_srand(doubleval(microtime()) * 100000000);
//choose banner
switch(mt_rand(1,3))
{
case 1:
$bannerURL = "http://www.leonatkinson.com/random/";
$bannerImage = "leon_banner.png";
break;
case 2:
$bannerURL = "http://www.php.net/";
$bannerImage = "php_banner.png";
break;
default:
$bannerURL = "http://www.phptr.com/";
$bannerImage = "phptr_banner.png";
}
//display banner
print("<a href=\"$bannerURL\">");
print("<img src=\"$bannerImage\" ");
print("width=\"400\" height=\"148\" border=\"0\">");
print("</a>");
?>
 |