php 从 HTTP_REFERER 中提取 Scheme 和 Host
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1144856/
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
Extract Scheme and Host from HTTP_REFERER
提问by jiexi
I have $_SERVER['HTTP_REFERER']— pretend it is http://example.com/i/like/turtles.html. What would I need to do to get just the http://example.compart out of the string, and store it in its own variable?
我有$_SERVER['HTTP_REFERER']- 假装它是http://example.com/i/like/turtles.html。我需要做什么才能从http://example.com字符串中取出一部分并将其存储在自己的变量中?
回答by Sampson
In this example, the best solution would be to use PHP's parse_urlmethod. This splits up the URL into an associative array. You would then build your final value by combining the schemewith the host:
在这个例子中,最好的解决方案是使用 PHP 的parse_url方法。这会将 URL 拆分为关联数组。然后,您将通过将scheme与结合来构建您的最终价值host:
if ( $parts = parse_url( "http://example.com/i/like/turtles.html" ) ) {
echo $parts[ "scheme" ] . "://" . $parts[ "host" ];
}
回答by Adam Wright
回答by Jani Hartikainen
You should be able to use the parse_url functionto achieve that
您应该能够使用parse_url 函数来实现
回答by Gumbo
You could use a regular expression:
您可以使用正则表达式:
if (isset($_SERVER['HTTP_REFERER']) && preg_match('@^[^/]+://[^/]+@', $_SERVER['HTTP_REFERER'], $match)) {
var_dump($match[0]);
}
Or you could use the parse_urlfunction.
或者您可以使用该parse_url功能。

