Question

I am racking my brain as to why this isn't working.

What I would like to achieve, is to restrict access to a page on my own Website, only if coming from a certain website, Facebook for instance.

Since a link will be posted on 1 or more Facebook pages and/or my personal profile, would like the script to execute if coming from Facebook and/or any other "PAGES" it's posted on.

For instance, if I post my link on www.facebook.com/This_is_my_PAGE or is posted on my personal profile www.facebook.com/freds_personal_profile or someone shares my link on Facebook, would like the page accessible only to those coming from the Facebook domain.

I found the script below while searching for a solution, but it's echoing my error message, instead of redirecting to the link in question.

$target_site = 'https://www.facebook.com/';
if (isset($_SERVER['HTTP_REFERER']) && preg_match("/$target_site/",$_SERVER['HTTP_REFERER'])) {
// do something with people from facebook.com
} 

else {
// do something else with everyone else

echo "Sorry, viewable to Facebook fans only.";

}
Was it helpful?

Solution

First of all, your code is flawed because:

  • What if the user is not using Facebook's "Secure version" (http rather than https)?
  • What if the user is coming from facebook.com rather than www.facebook.com?
  • What if a malicious user is tricking users into coming from a site like http://example.com/evilpage.php?https://www.facebook.com/?

The main reason it doesn't work is because your regex is completely invalid. Instead, it should be along the lines of:

preg_match("/".preg_quote($target_site,"/")."/i",$_SERVER['HTTP_REFERER']);

(documentation on preg_quote())

Aside from all of this, there is no security in checking the referrer. It can be changed, it can e blocked altogether. It should not be relied on.

OTHER TIPS

Facebook hooks up external links to the http protocol, not https. Change your target site to this:

$target_site = 'http://www.facebook.com/';

You can confirm this by right-clicking a link posted in facebook and copying it to the clipboard (then pasting it). You'll see it looks like this:

`http://www.facebook.com/l.php?u=...`

This is the case regardless of whether you are actually browsing with https or http.

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