Monday, May 13, 2013

Describe how to create a simple AD rotator script without using database in PHP 


Following are the steps to create a simple AD rotator script without using database in PHP:-
All the ad’s can be collected in one place and be displayed randomly.rand() function can be used for this purpose.

  • In order to NOT use any database, a flat file can be used to store the ad’s.
  • In order to store the Ad’s information (HTML code), a flat file say “ad.txt” can be created.
  • The random number can be stored in a variable 
  • $result_random=rand(1, 100);
  • Conditions can be checked to display the ad’s.
  • if($result_random<=70)
  • {
  •       echo "Display ad1";
  • }


First create a text file with ads.txt extension. Each ad has its unique HTML code. For example :
<a href="http://www.mysite.com">Demo Text Link</a>
Write a function to handle ads. Example :
<?php
// Function to display random ads from a list 
function showRandomAD($ADnumber = 1){
// Loading the ad list into an array
$adList = file('ads.txt');

// Check the total number of ads
$numberOfADs = sizeof($adList);

// Initialize the random generator
list($usec, $sec) = explode(' ', microtime());
srand((float) $sec + ((float) $usec * 100000));

// Initialize the ads counter
$adCount = 0;

// Loop to display the requeste number of ads
while ($adCount++ < $ADnumber) {
// Generate random ad id
$actAD = rand(0, $numberOfADs-1);
// Display the above generated ad from the array
echo $adList[$actAD].'<br/>';
}
}
?>
All the lines from the file is stored in the array.
The function srand() selects the adds randomly from the array.
Create a simple php file and ember the statement <?php showRandomAD(3); ?> to demonstrate the use of rotator ad.

No comments:

Post a Comment