# Redirect incoming traffic based on referrer or random number

This working script directs incoming traffic to different locations depending on the value present in the session for referring URI. If there is a present value, it sends the user back to their original location. If not, then a random number is generated, checked against and used to direct the visitor to one of two possible locations, each with a likelihood of 50%.

It satisfies the basic requirement but I'm wondering if there might not be a better approach.

We have two sub directories, each one with a file within it, and one file at the root. Traffic generally hits the files in the sub dirs, but I wanted to create a root file to handle an event where a user might strip out everything in the URL but the domain.

Each of the files in the sub dirs use this logic to set the referrer:

function strleft($s1,$s2) {
return substr($s1, 0, strpos($s1, $s2)); } function selfURL() { if(!isset($_SERVER['REQUEST_URI'])) {
$serverrequri =$_SERVER['PHP_SELF'];
} else {
$serverrequri =$_SERVER['REQUEST_URI'];
}
$s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";$protocol = strleft(strtolower($_SERVER["SERVER_PROTOCOL"]), "/").$s;
$port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);$_SESSION['ref'] = $protocol."://".$_SERVER['SERVER_NAME'].$port.$serverrequri;
}
selfURL();


The file at the root uses this logic to direct traffic:

$refurl =$_SESSION['ref'];
if (isset($refurl)) { header("Location: " .$refurl);
} else {
$loc1 = "dir1/file.php";$loc2 = "dir2/file.php";
$num = mt_rand(1, 100); if ($num > 50) {
header("Location: " . $loc1); } else { header("Location: " .$loc2);
}
}

• Are you trying to reimplement PHP sessions? What is the purpose? You might want to read this: php.net/manual/en/book.session.php Aug 10 '11 at 19:07
• is there any way "$_SERVER['REQUEST_URI']" wont be set? Aug 11 '11 at 7:15 • This is pretty much decent code from my read. Don't expect you to get a lot of comments or answers as this is basically clean and proper from a language agnostic design perspective.. Aug 14 '11 at 3:13 ## 1 Answer null coalesce does exist in php according to the google (per: https://stackoverflow.com/questions/1013493/coalesce-function-for-php ) $s = $_SERVER["HTTPS"] ?: "";$protocol = strleft(strtolower($_SERVER["SERVER_PROTOCOL"]), "/").$s;


I'm not super familiar with php, but I think this should work from what I understand you're doing here.

• nice! very useful, indeed. Dec 14 '11 at 8:44