<?php
//	Path to the file and file name
define('FILE_NAME', 'data/rotator_data.dat');
define('URL_INDEX', 'data/url_index.dat');

//	Let's start by loading the URLs if there are any.
//	Holds URLs that we get from a file
$urls = array();

//	Load file and get URLs
if (file_exists(FILE_NAME))
{
	//	Try to open the file
	$handle = fopen(FILE_NAME, 'r');

	//	If file is opened, read it line by line and save data into array
	if ($handle) 
	{
		while (($buffer = fgets($handle, 4096)) !== false) 
		{
			$urls[] = $buffer;
		}
		
		//	If error is found, kill the script and say it
		if (feof($handle) == false) 
		{
			echo 'Problem reading the file!';
			die();
		}
		
		fclose($handle);
	}
}
else
{
	//	If file doesn't exist, tell
	echo 'Database not found!';
	die();
}

//	Check if there are any URLs in the file, if not, kill the execution and tell it
if (count($urls) == 0 || is_array($urls) == false)
{
	echo 'Oops, no URLs found in database!';
	die();
}

$index_key = '0';

//	Right, now let's load the file that holds the last URL index key that was redirected
//	Load file and get URLs
if (file_exists(URL_INDEX))
{
	//	Try to open the file
	$index_key = file_get_contents(URL_INDEX);
}
else
{
	//	If file doesn't exist, let's create it!
	file_put_contents(URL_INDEX, '');
}

//	Now that we have all the required data, let's get the URL that needs to be used
//	for redirection.
if (isset($urls[($index_key + 1)]) == false)
{
	//	Next index key not found? Let's start from 0 then ;)
	$final_url_key_index = 0;
}
else
{
	$final_url_key_index = ($index_key + 1);
}

//	Before redirection, let's save the index key that we just used
file_put_contents(URL_INDEX, $final_url_key_index);

//	All good, so let's set the header and redirect to the final URL
header('HTTP/1.0 200 OK');
header('Location: '.$urls[$final_url_key_index]);
die();
?>