Rotating ads in order

Discussion in 'PHP' started by mnymkr, Sep 14, 2007.

  1. #1
    I see a bunch of scripts for ad rotation based on the random function

    but how can i rotate ads in order every time a page refreshes?

    first showing ad1 second ad2 etc
     
    mnymkr, Sep 14, 2007 IP
  2. lwbbs

    lwbbs Well-Known Member

    Messages:
    331
    Likes Received:
    13
    Best Answers:
    0
    Trophy Points:
    108
    #2
    use file or database to recorder the current index

     
    lwbbs, Sep 14, 2007 IP
  3. mnymkr

    mnymkr Well-Known Member

    Messages:
    2,328
    Likes Received:
    32
    Best Answers:
    0
    Trophy Points:
    120
    #3
    how would i do it with a file?
     
    mnymkr, Sep 14, 2007 IP
  4. sea otter

    sea otter Peon

    Messages:
    250
    Likes Received:
    23
    Best Answers:
    0
    Trophy Points:
    0
    #4
    First, create a text file containing the ads, and call it ads.txt. Put one ad on each line

    
    ad text 1
    ad text 2
    ad text 3
    
    Code (markup):
    Next, use this code to display each ad in sequence as you visit the page. The code below stores the current ad counter in a file, so make sure you have write permissions wherever you decide to store the file.

    If the file does not exist, the script creates it and start the ad counting at the first ad. When the last ad is reached, the script starts over at the first ad.

    
    <?php
    
    // set these to your counter file name and ad links file name
    // make sure you have WRITE permissions on the counter.txt file!
    $counter_file = './counter.txt';
    $ads_file = './ads.txt';
    
    // first retrieve the ads so that we know how many there are
    $ads = @file($ads_file,FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    
    // TODO: you might want to do something if no ads or ads are missing!
    
    // now retrieve the next ad to display and update the counter in the file
    if (($fh = @fopen($counter_file,'a+')) === false)
    	$ad=0;
    else
    {
    	@flock($fh,LOCK_EX);
    	@fseek($fh,0);
    	$ad=@fgets($fh);
    	if ($ad === false)
    		$ad = 0;
    	else
    	{
    		$ad = intval($ad);
    		// past the end of the ads? start over
    		if ($ad >= count($ads))
    			$ad = 0;
    	}
    	@ftruncate($fh,0);
    	@fputs($fh, $ad+1);
    	@flock($fh,LOCK_UN);
    	@fclose($fh);
    }
    
    // now get the actual ad text to display
    $current_ad = $ads[$ad];
    
    // and echo it out, or do whatever you need with it
    echo $current_ad;
    ?>
    
    PHP:
     
    sea otter, Sep 14, 2007 IP
  5. mnymkr

    mnymkr Well-Known Member

    Messages:
    2,328
    Likes Received:
    32
    Best Answers:
    0
    Trophy Points:
    120
    #5
    thanks!!!!
     
    mnymkr, Sep 17, 2007 IP
  6. lwbbs

    lwbbs Well-Known Member

    Messages:
    331
    Likes Received:
    13
    Best Answers:
    0
    Trophy Points:
    108
    #6
    lwbbs, Sep 17, 2007 IP