Let's say there are 3 links:
How would I go about creating a rotational based redirect system?
Here's how it would work:
The user opens up http://example.com and then gets redirected to http://example.com/1
The URL http://example.com/1
(that the user gets redirected to is stored in a text file with the URL as the value of the text file)
When another user visits http://example.com
, rather than getting redirected to http://example.com/1, he would get redirected to http://example.com/2. The code should know to redirect to http://example.com/2 rather than /1 as /1 is stored in the text file. After the user is redirected, the value of the text file changes from .../1 to .../2.
Same thing happens for when the next user visits but gets forwarded to .../3.
Fourth user gets redirected to .../1
And so on
<?php
$link[0] = array('link' => 'http://example.com/1', 'percent' => 33);
$link[1] = array('link' => 'http://example.com/2', 'percent' => 33);
$link[2] = array('link' => 'http://example.com/3', 'percent' => 33);
$percent_arr = array();
foreach($link as $k => $_l) {
$percent_arr = array_merge($percent_arr, array_fill(0, $_l['percent'], $k));
}
$random_key = $percent_arr[mt_rand(0,count($percent_arr)-1)];
$redirectlink = $link[$random_key]['link'];
?>
<a href="<?php $redirectlink ?>">Click to redirect</a>
I am currently using this code but it doesn't provide me with what is needed.
If you are using a database with your script, I would recomend using timestamps:
You create a table with 3 columns, id
siteurl
lastvisit
.
Create a query which gets the site which was visited the longest ago.
When the user enters your site, he gets redirected to where he belongs. The timestamp of the site gets updated.
If you don't have a database, just use .txt's.
If I understand your text right, you don't need weighted routing, so
just store the index of the next route in your text file and rotate it on every call.
Read file:
$link[0] = array('link' => 'http://example.com/1');
$link[1] = array('link' => 'http://example.com/2');
$link[2] = array('link' => 'http://example.com/3');
$next = intval(file_get_contents('next.txt')); // $next -> 0
$redirectTo = $link[$next];
Now rotate and write file:
$next = ($next === 2) ? 0 : next +1;
file_put_contents('next.txt', $next);
//redirect ...