PHP 仅允许访问特定的引荐来源网址/页面
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14854117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP Allow access to specific referrer url/page only
提问by C0nw0nk
So my question is simple ive used the following method for allowing access to the php script via the referrer's domain name but i want to allow access for only referrers matching the full url.
所以我的问题很简单我使用以下方法允许通过引用者的域名访问 php 脚本,但我想只允许访问匹配完整 url 的引用者。
<?php
if (isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER'] != 'domain.com')
{
echo "Eexcuting code here";
} else {
echo('Hot Linking Not Permitted');
// display some message / image / video
exit;
}
?>
So if the referrer url matches http://www.domain.com/page.htmlthen allow access else if block it.
因此,如果引荐来源网址与http://www.domain.com/page.html匹配,则如果阻止它,则允许其他访问。
回答by Gargron
It will not be safe because referrer data can be easily spoofed. However, if it still fits your needs, then you should be fine with your code already, since $_SERVER['HTTP_REFERER']contains the full referrer URL and not just the domain. Actually, your present code needs some adjustments because it can't work like that:
这将是不安全的,因为引用数据很容易被欺骗。但是,如果它仍然满足您的需求,那么您的代码应该已经没问题了,因为$_SERVER['HTTP_REFERER']包含完整的引用 URL 而不仅仅是域。实际上,您当前的代码需要一些调整,因为它不能像那样工作:
<?php
// This is to check if the request is coming from a specific domain
$ref = $_SERVER['HTTP_REFERER'];
$refData = parse_url($ref);
if($refData['host'] !== 'domain.com') {
// Output string and stop execution
die("Hotlinking not permitted");
}
echo "Executing code here";
?>
Note that if you check if HTTP_REFERER is set before checking if it's what you want, people would get to your script without any referrer set at all, so you should check it in any case. Now, checking for a specific URL is much simpler:
请注意,如果您在检查 HTTP_REFERER 是否已设置之前检查它是否是您想要的,人们会在根本没有设置任何引用者的情况下访问您的脚本,因此您应该在任何情况下检查它。现在,检查特定的 URL 就简单多了:
<?php
// This is to check if the request is coming from a specific URL
$ref = $_SERVER['HTTP_REFERER'];
if($ref !== 'http://domain.com/page.html') {
die("Hotlinking not permitted");
}
echo "Executing code here";
?>
回答by fronbow
What is it that you are trying to protect?
你想要保护的是什么?
You should never trust HTTP_REFERER as it can be spoofed (as others have pointed out). Also some firewalls and security software will rewrite or remove the referer, and not all browsers report it properly.
您永远不应该相信 HTTP_REFERER,因为它可以被欺骗(正如其他人指出的那样)。此外,一些防火墙和安全软件会重写或删除引用,并非所有浏览器都能正确报告。
If it's sensitive data then personally I would pass a hash between pages.
如果它是敏感数据,那么我个人会在页面之间传递一个哈希值。

