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 &gt; 50) {
        header("Location: " . $loc1);
    } else {
        header("Location: " . $loc2);
    }
}
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.