Restricting access if not coming from certain referer(s) PHP

半城伤御伤魂 提交于 2019-12-12 14:46:25

问题


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.";

}

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/11022275/restricting-access-if-not-coming-from-certain-referers-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!