문제

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?

도움이 되었습니까?

해결책

<?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

다른 팁

It could be done without a database, yes. You could create a simple script with an arbitrary array of URLs and a text file with a number in it. The number tracks the index of the array for the URL to display. When the script is loaded, read the file, get the number, and display the associated URL. Then increment the number and write it back to the file unless the number now exceeds the size of the array - then write a zero back to the file.

To accomplish this with the URLS in a file (and no counter), put all the URLs on a single line of text. Separate them with the | pipe character. On the following line, put a zero. Read in the first line and explode on the pipe character to make an array. Get the first element from the array, use that URL, and move the first array element to the end of the array. Implode the array with the pipe character back to a string and overwrite the file contents to the text file.

Depending on your plan, this will or won't work with cookies. Since cookies are stored in the client browser, you can only track what the individual visitor has seen. If the entire audience needs to be considered, this will not help because you'd need a group array index to track, not an individual one.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top