php 如何仅从 $_SERVER['HTTP_REFERER']; 中选择根域?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9049997/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 06:02:55  来源:igfitidea点击:

How do I select only the root domain from $_SERVER['HTTP_REFERER'];?

phpdnshttp-status-code-404http-referer

提问by Nathan Bunn

I want to have a 404 page that can detect if a user has come to that page either via my site, via my shortened URL or via another site, and I am making it using PHP. I am slowly getting to grips with PHP and this may well be a simple question, but I am quite tired to be honest and have no caffeine in my system, and I am wanting to tie up any loose ends in my portfolio as soon as possible.

我想要一个 404 页面,它可以检测用户是否通过我的站点、我的缩短 URL 或其他站点访问了该页面,并且我正在使用 PHP 进行访问。我正在慢慢掌握 PHP,这很可能是一个简单的问题,但老实说我很累,我的系统中没有咖啡因,我想尽快解决我的投资组合中的任何松散问题.

I have found the $_SERVER['HTTP_REFERER'];PHP variable gives me the entire URL, which is a start. Is there a way that this can give me only the root domain, either via another variable or a function, bearing in mind that some referrers may be using http:// and some https:// (so simply starting from the seventh character would not always work)? That way, I can match the URL based on two (or more) predefined addresses and produce the content that relates to that domain.

我发现$_SERVER['HTTP_REFERER'];PHP 变量给了我整个 URL,这是一个开始。有没有办法通过另一个变量或函数只给我根域,记住一些引用者可能使用 http:// 和一些 https:// (所以简单地从第七个字符开始并不总是有效)?这样,我可以根据两个(或多个)预定义地址匹配 URL,并生成与该域相关的内容。

回答by deceze

parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST)

See http://php.net/manual/en/function.parse-url.php.

请参阅http://php.net/manual/en/function.parse-url.php

Note though that the referer is terrifically easy to spoof, so it's hardly reliable.

请注意,referer 非常容易被欺骗,因此它几乎不可靠。

回答by Dan LaManna

http://php.net/manual/en/function.parse-url.phpmay be your best bet, although you could use a regular expression to achieve what you're looking for easily as well.

http://php.net/manual/en/function.parse-url.php可能是您最好的选择,尽管您也可以使用正则表达式轻松实现您正在寻找的内容。

回答by Matoeil

this should do :

这应该做:

 $_SERVER['SERVER_NAME']