1

I need to execute a PHP script only is a user is redirected from another page that starts with specific name. For example: domain.com/abcXXXXXX

I've tried this but it doesn't seem to work:

if (preg_match("/abc", $_SERVER['HTTP_REFERER'])) {

}

What am I missing?

santa
  • 12,234
  • 49
  • 155
  • 255
  • 2
    you shouldn't use `$_SERVER['HTTP_REFERER']` it's not reliable. You can use `strpos()` or `stripos()`. – Funk Forty Niner Dec 02 '15 at 16:35
  • 1
    `"/abc"` is not a regex pattern – Quentin Dec 02 '15 at 16:35
  • 1
    The pattern lacks delimiters, which should give you a warning. – syck Dec 02 '15 at 16:36
  • I changed "/abc" to "%/abc%" and it seem to be working now... – santa Dec 02 '15 at 16:38
  • 1
    Keep in mind what @Fred-ii- said. From the docs: *"'HTTP_REFERER' The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted."* – Jay Blanchard Dec 02 '15 at 16:39
  • 1
    Great but you need to read this http://stackoverflow.com/a/6023980/ about `$_SERVER['HTTP_REFERER']`. – Funk Forty Niner Dec 02 '15 at 16:39

2 Answers2

1

I would suggest using parse_url in conjunction with a look up table of URLs.

You can do the following:

$allowedReferals = [
    'www.google.com/maps',
    'www.google.co.uk/maps',
    'www.google.in/maps',
];

$referer = !isset($_SERVER['HTTP_REFERER']) ? null : parse_url($_SERVER['HTTP_REFERER']);

if (!is_null($referer)) {
    $host = !isset($referer['host']) ? null : $referer['host'];
    $path = !isset($referer['path']) ? null : $referer['path'];
    $referingDomain = $host . $path;

    if (in_array($referingDomain, $allowedReferals)) {
        // The referer matches one of the allowed referers in the lookup table
        // Do something...
    }

    if (preg_match('/^maps/', $path)) {
        // The referer's path begins with maps
        // Do something...
    }
}
Enijar
  • 6,387
  • 9
  • 44
  • 73
0

Fix the regex pattern like this:

if (preg_match("/^domain\.com\/abc/", $_SERVER['HTTP_REFERER'])) {

}

Another version to check with/without www:

if (preg_match("/[w{3}\.]?domain\.com\/abc/",'www.domain.com/abcXXXXXX')) {

}
Oli
  • 2,370
  • 2
  • 26
  • 42
  • I would recommend not to use the `^` at pattern start in case the domain is prefixed with for example _www._. – syck Dec 02 '15 at 16:38
  • True, updated my answer. Although it could be extended further to check http(s) also, but it all depends on the requirements.. – Oli Dec 02 '15 at 16:43