Question

I am trying to redirect on loading the page but i want it to be 50% of the time , to page1.php and 50% to page2.php

Any idea how can I write it in PHP? do I store it in an Array or how could I do that?

Thanks in advance

Was it helpful?

Solution

Pretty short script. Use the built-in PHP function mt_rand($min, $max).

if (mt_rand(0,1) == 0) {
    header('Location: http://example.com/redirect1/');
    exit;
} else {
    header('Location: http://example.com/redirect2/');
    exit;
}

Or as a ternary, which can be a little less readable if not using variables:

header(mt_rand(0,1) == 0 ? 'Location: http://example.com/redirect1/' : 'Location: http://example.com/redirect2/');
exit;

Or using variables:

$redirect1 = 'http://example.com/redirect1/';
$redirect2 = 'http://example.com/redirect2/';
header('Location: ' . mt_rand(0,1) == 0 ? $redirect1 : $redirect2);
exit;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top