Question

I'm using an if statement along with PHP's $_SERVER['HTTP_REFERER'] to check if users came from the home page and perform some functions if they did:

if($_SERVER['HTTP_REFERER'] == htttp://www.example.com {
//some code
}

The problem is that the homepage will sometimes be passing GET variables in the URL and PHP's $_SERVER['HTTP_REFERER'] method considers a URL with a GET variable as a different URL and therefore won't trigger the if function unless the user comes from the home page without passing a GET variable.

I'd like to trigger the if statement when someone comes from the home page regardless of whether a GET variable is passed, any help would be greatly appreciated!

Was it helpful?

Solution

The easiest way is to check if HTTP_REFERER starts with the URL you want:

if (strpos($_SERVER['HTTP_REFERER'], 'http://www.example.com') === 0)) {

OTHER TIPS

@EmilyShepherd's answer should work.

This, though, would check for just the domain. This is advantageous because some sites allow the omitting of (www.) and others may even be reachable through both (https://) and (http://).

if (strpos($_SERVER['HTTP_REFERER'], 'example.com')) {/*If refer contains example.com*/}

As an aside, be mindful that refers can be easily spoofed.

You can also try using this

$url = $_SERVER['HTTP_REFERER'];
$data = parse_url($url);
$referer= $data['host'];

if($referer== 'www.example.com') {
    // Some codes here
}

/*
var_dump($data);
Array
(
    [scheme] => http
    [host] => www.example.com
    [path] => /path/to/
    [query] => here=there
)
*/

With this, you can even extract paths and query string of the referer.

NOTE: If your scheme could be either http of https, it would be better to just extract the host name which would be www.example.com for matching.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top