Search code examples
phpurlrotator

URL rotator in specific order


I want to create an URL rotator script that will rotate my URLs in a specific order,not randomly.

let say I have 100 URLS to rotate, I have them ordered and the rotator will show them from the first one until the last one, then return to the first URL and so on.

if possible can it be a simple php script with no database?


Solution

  • <?php
    define('FILEDB', 'count.db');
    define('URLDB', 'url.db');
    
    function readURLS()
    {
      $fp = fopen(URLDB, 'r');
    
      if( null == $fp )
        return false;
    
      $retval = array();
      while (($line = fgets($fp)) !== false)
      {
        $retval[] = $line;
      }
    
      return $retval;
    }
    
    $list = readURLS();
    
    if( false === $list )
    {
      echo "No URLs available";
    }
    else
    {
      $fp = fopen(FILEDB, 'a+');
    
      $count = (fread($fp, filesize(FILEDB)) + 1) % count($list);
    
      ftruncate($fp, 0);
      fwrite($fp, "{$count}");
      fclose($fp);
    
      echo $list[$count];
    }
    

    this works.


    updated with new requirements.
    You'll need a file named url.db (or whatever you fill in after the define('URLDB', 'xxx') Each line is an URL entry.

    count.db can exist, but doesn't need to. It is better to create one with a simple 0 in it.

    It will rotate through all URL entries in the url.db file on each 'request'.

    However this is not concurrent safe. If person A requests the page and person B does as well there might be a chance that A and B see the same URL if B reads count.db before A has written the new contents to count.db