PHP Redirect Based on HTTP Referer

Hoping someone can help.

I have a file, say bounce.php that uses php url ramdomizer, like this:

[php]<?php
$urls = array(“link1”,
“link2”);
$url = $urls[array_rand($urls)];
header(“Location: http://$url”);
?> [/php]

What I want is to only allow that code to execute if the user is coming from another php page on the same sever/folder. So like this…

So bounce.php will check where the traffic is coming from…if traffic is coming from page1.php (file on same server) then it will allow URL REDIRECT CODE to execute, if traffic is coming from another source, such as google.com, or from no referel, then person is sent to another site, say msn.com.

First of all, you’d get the referrer, then check it. This example below only uses two referral sites so therefore has them in an IF:

[php]if(isset($_SERVER[‘HTTP_REFERER’])) {
$referrer = $_SERVER[‘HTTP_REFERER’];
} else {
$referrer = ‘’;
}

if($referrer == ‘’) {
// Not OK (no referrer set)
} else if($referrer == ‘http://your-site.com/some_page.php’ || $referrer = ‘http://your-site.com/some_page2.php’) {
// OK
} else {
// Not OK (referrer from other site)
}[/php]

If you’ve got lots of pages, you could store the allowed pages inside of an array and then check to see if the item exists inside the array.

[php]if(isset($_SERVER[‘HTTP_REFERER’])) {
$referrer = $_SERVER[‘HTTP_REFERER’];
} else {
$referrer = ‘’;
}

$allowed_referrers = array(‘http://your-site.com/page1.php’, ‘http://your-site.com/page2.php’, ‘http://your-site.com/page3.php’);

if($referrer == ‘’) {
// Not OK (no referrer set)
} else if(in_array($referrer, $allowed_referrers) {
// OK
} else {
// Not OK (referrer from other site)
}[/php]

Alternatively, you could just check that the referrer starts with your website’s address:

[php]if(isset($_SERVER[‘HTTP_REFERER’])) {
$referrer = $_SERVER[‘HTTP_REFERER’];
} else {
$referrer = ‘’;
}

if($referrer == ‘’) {
// Not OK (no referrer set)
} else if(substr($referrer, 0, strlen(‘http://your-site.com’)) == ‘http://your-site.com’) {
// OK
} else {
// Not OK (referrer from other site)
}[/php]

Sponsor our Newsletter | Privacy Policy | Terms of Service