PHP 检查 URL 是否包含查询字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7864237/
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 to check if a URL contains a query string
提问by dennisbest
This is an easy one. There seem to be plenty of solutions to determine if a URL contains a specific key or value, but strangely I can't find a solution for determining if URL does or does not have a query at all.
这是个简单的。似乎有很多解决方案可以确定 URL 是否包含特定的键或值,但奇怪的是,我找不到用于确定 URL 是否有查询的解决方案。
Using PHP, I simply want to check to see if the current URL has a query string. For example: http://abc.com/xyz/?key=valueVS. http://abc.com/xyz/.
使用 PHP,我只想检查当前 URL 是否有查询字符串。例如:http://abc.com/xyz/ ?key=value VS。http://abc.com/xyz/。
回答by deceze
For any URL as a string:
对于任何 URL 作为字符串:
if (parse_url($url, PHP_URL_QUERY))
If it's for the URL of the current request, simply:
如果是针对当前请求的 URL ,只需:
if ($_GET)
回答by rzyns
The easiest way is probably to check to see if the $_GET[]
contains anything at all. This can be done with the empty()
function as follows:
最简单的方法可能是检查是否$_GET[]
包含任何内容。这可以通过以下empty()
函数完成:
if(empty($_GET)) {
//No variables are specified in the URL.
//Do stuff accordingly
echo "No variables specified in URL...";
} else {
//Variables are present. Do stuff:
echo "Hey! Here are all the variables in the URL!\n";
print_r($_GET);
}
回答by mickadoo
parse_url
seems like the logical choice in most cases. However I can't think of a case where '?' in a URL would not denote the start of a query string so for a (very minor) performance increase you could go with
parse_url
在大多数情况下似乎是合乎逻辑的选择。但是我想不出'?'的情况。在 URL 中不会表示查询字符串的开始,因此对于(非常小的)性能提升,您可以使用
return strpos($url, '?') !== false;
return strpos($url, '?') !== false;
Over 1,000,000 iterations the average time for strpos was about 1.6 seconds vs 1.8 for parse_url. That being said, unless your application is checking millions of URLs for query strings I'd go for parse_url
.
超过 1,000,000 次迭代,strpos 的平均时间约为 1.6 秒,而 parse_url 的平均时间为 1.8 秒。话虽如此,除非您的应用程序正在检查数百万个 URL 中的查询字符串,否则我会选择parse_url
.
回答by PHP
Like this:
像这样:
if (isset($_SERVER['QUERY_STRING'])) {
}