HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Redirect incoming traffic based on referrer or random number

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
randomreferrernumbertrafficincomingredirectbased

Problem

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);
    }
}

Solution

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.

Code Snippets

$s = $_SERVER["HTTPS"] ?: "";
$protocol = strleft(strtolower($_SERVER["SERVER_PROTOCOL"]), "/").$s;

Context

StackExchange Code Review Q#4018, answer score: 3

Revisions (0)

No revisions yet.