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);
}
}
-
\$\begingroup\$ Are you trying to reimplement PHP sessions? What is the purpose? You might want to read this: php.net/manual/en/book.session.php \$\endgroup\$dotancohen– dotancohen2011年08月10日 19:07:48 +00:00Commented Aug 10, 2011 at 19:07
-
1\$\begingroup\$ is there any way "$_SERVER['REQUEST_URI']" wont be set? \$\endgroup\$Quamis– Quamis2011年08月11日 07:15:49 +00:00Commented Aug 11, 2011 at 7:15
-
1\$\begingroup\$ 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.. \$\endgroup\$Jimmy Hoffa– Jimmy Hoffa2011年08月14日 03:13:56 +00:00Commented Aug 14, 2011 at 3:13
1 Answer 1
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.
-
\$\begingroup\$ nice! very useful, indeed. \$\endgroup\$Dalex– Dalex2011年12月14日 08:44:17 +00:00Commented Dec 14, 2011 at 8:44