-3

I've just trying to set 'if' rules for my website, and I'm facing with little problem I want to allow:

if ($_SERVER["HTTP_REFERER"] = "http://t.co/XXXXXX")
{ allowed }

XXXXXX - unique end of each link, so I need to set that every visit, which begins with t.co would be accepted. How can I do that? Thanks in advance.

  • [PHP string functions](http://php.net/manual/en/ref.strings.php) – Jocelyn Jul 22 '14 at 22:39
  • 3
    *"Using `HTTP_REFERER` isn't reliable, it's value is dependent on the HTTP Referer header sent by the browser or client application to the server and therefore can't be trusted."* - [**Read more...**](http://stackoverflow.com/a/6023980/) – Funk Forty Niner Jul 22 '14 at 22:42
  • 1
    If your plan is to use referrer to implement something important such as security or some such, then you need to change your plan. HTTP_REFERRER is completely untrustworthy and can be spoofed with virtually no effort. – GordonM Jul 22 '14 at 22:47
  • [`int stripos ( string $haystack , string $needle [, int $offset = 0 ] );`](http://php.net/stripos) – Daniel W. Jul 22 '14 at 22:48

3 Answers3

4

Use the following snippet:

if (preg_match('/^https?:\/\/t\.co\//', $_SERVER['HTTP_REFERER'])) {
    # allowed
}

This will also match https requests, by the way.

Alternatively, you can use parse_url, like this:

$parsed = parse_url($_SERVER['HTTP_REFERER']);
if ($parsed['host'] === 't.co') {
    # allowed
}

Keep in mind though that $_SERVER['HTTP_REFERER'] might not be set or empty, thus an additional

if (isset($_SERVER['HTTP_REFERER']))

is useful in both cases.

brainbowler
  • 667
  • 5
  • 17
0

Just compare the first 12 characters:

if (substr($_SERVER["HTTP_REFERER"],0,12) == "http://t.co/" || substr($_SERVER["HTTP_REFERER"],0,13) == "https://t.co/")
{ allowed }
Rich Bradshaw
  • 71,795
  • 44
  • 182
  • 241
0

My try:

if (stripos($_SERVER["HTTP_REFERER"], '://t.co/') === 4
 || stripos($_SERVER["HTTP_REFERER"], '://t.co/') === 5) {
    // Allowed
Daniel W.
  • 31,164
  • 13
  • 93
  • 151