php 获取 URL 查询字符串参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8469767/
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
Get URL query string parameters
提问by enloz
What is the "less code needed" way to get parameters from a URL query string which is formatted like the following?
从格式如下的 URL 查询字符串获取参数的“所需代码更少”的方法是什么?
www.mysite.com/category/subcategory?myqueryhash
www.mysite.com/category/subcategory?myqueryhash
Output should be: myqueryhash
输出应该是: myqueryhash
I am aware of this approach:
我知道这种方法:
www.mysite.com/category/subcategory?q=myquery
<?php
echo $_GET['q']; //Output: myquery
?>
回答by Filip Roséen - refp
$_SERVER['QUERY_STRING']
contains the data that you are looking for.
$_SERVER['QUERY_STRING']
包含您要查找的数据。
DOCUMENTATION
文件
回答by medina
The PHP way to do it is using the function parse_url, which parses a URL and return its components. Including the query string.
PHP 的方法是使用函数parse_url,它解析一个 URL 并返回它的组件。包括查询字符串。
Example:
例子:
$url = 'www.mysite.com/category/subcategory?myqueryhash';
echo parse_url($url, PHP_URL_QUERY); # output "myqueryhash"
回答by sbrbot
The function parse_str()
automatically reads all query parameters into an array.
该函数parse_str()
自动将所有查询参数读入一个数组。
For example, if the URL is http://www.example.com/page.php?x=100&y=200
, the code
例如,如果 URL 是http://www.example.com/page.php?x=100&y=200
,则代码
$queries = array();
parse_str($_SERVER['QUERY_STRING'], $queries);
will store parameters into the $queries
array ($queries['x']=100
, $queries['y']=200
).
将参数存储到$queries
数组 ( $queries['x']=100
, $queries['y']=200
) 中。
Look at documentation of parse_str
EDIT
编辑
According to the PHP documentation, parse_str()
should only be used with a second parameter. Using parse_str($_SERVER['QUERY_STRING'])
on this URL will create variables $x
and $y
, which makes the code vulnerable to attacks such as http://www.example.com/page.php?authenticated=1
.
根据 PHP 文档,parse_str()
只能与第二个参数一起使用。parse_str($_SERVER['QUERY_STRING'])
在此 URL 上使用将创建变量$x
and $y
,这使得代码容易受到诸如http://www.example.com/page.php?authenticated=1
.
回答by Jason T Featheringham
If you want the whole query string:
如果你想要整个查询字符串:
$_SERVER["QUERY_STRING"]
回答by user3816325
I will recommended best answer as
我会推荐最佳答案为
<?php
echo 'Hello ' . htmlspecialchars($_GET["name"]) . '!';
?>
<?php
echo 'Hello ' . htmlspecialchars($_GET["name"]) . '!';
?>
Assuming the user entered http://example.com/?name=Hannes
假设用户输入了http://example.com/?name=Hannes
The above example will output:
上面的例子将输出:
Hello Hannes!
你好汉尼斯!
回答by K. Shahzad
Also if you are looking for current file name along with the query string, you will just need following
此外,如果您正在查找当前文件名以及查询字符串,您只需要遵循
basename($_SERVER['REQUEST_URI'])
It would provide you info like following example
它将为您提供如下示例的信息
file.php?arg1=val&arg2=val
file.php?arg1=val&arg2=val
And if you also want full path of file as well starting from root, e.g. /folder/folder2/file.php?arg1=val&arg2=val then just remove basename() function and just use fillowing
如果您还想要从根目录开始的完整文件路径,例如 /folder/folder2/file.php?arg1=val&arg2=val 那么只需删除 basename() 函数并使用填充
$_SERVER['REQUEST_URI']
回答by Adriana
Here is my function to rebuild parts of the REFERRER'squery string.
这是我重建REFERRER查询字符串部分的函数。
If the calling page already had a query string in its own URL, and you must go back to that page and want to send back some, not all, of that $_GET
vars (e.g. a page number).
如果调用页面在其自己的URL 中已经有一个查询字符串,并且您必须返回到该页面并想要发回一些,而不是全部,该$_GET
变量(例如页码)。
Example: Referrer's query string was ?foo=1&bar=2&baz=3
calling refererQueryString( 'foo' , 'baz' )
returns foo=1&baz=3"
:
示例:Referrer 的查询字符串正在?foo=1&bar=2&baz=3
调用refererQueryString( 'foo' , 'baz' )
返回foo=1&baz=3"
:
function refererQueryString(/* var args */) {
//Return empty string if no referer or no $_GET vars in referer available:
if (!isset($_SERVER['HTTP_REFERER']) ||
empty( $_SERVER['HTTP_REFERER']) ||
empty(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY ))) {
return '';
}
//Get URL query of referer (something like "threadID=7&page=8")
$refererQueryString = parse_url(urldecode($_SERVER['HTTP_REFERER']), PHP_URL_QUERY);
//Which values do you want to extract? (You passed their names as variables.)
$args = func_get_args();
//Get '[key=name]' strings out of referer's URL:
$pairs = explode('&',$refererQueryString);
//String you will return later:
$return = '';
//Analyze retrieved strings and look for the ones of interest:
foreach ($pairs as $pair) {
$keyVal = explode('=',$pair);
$key = &$keyVal[0];
$val = urlencode($keyVal[1]);
//If you passed the name as arg, attach current pair to return string:
if(in_array($key,$args)) {
$return .= '&'. $key . '=' .$val;
}
}
//Here are your returned 'key=value' pairs glued together with "&":
return ltrim($return,'&');
}
//If your referer was 'page.php?foo=1&bar=2&baz=3'
//and you want to header() back to 'page.php?foo=1&baz=3'
//(no 'bar', only foo and baz), then apply:
header('Location: page.php?'.refererQueryString('foo','baz'));
回答by aimiliano
This code and notation is not mine. Evan K solves a multi value same name query with a custom function ;) is taken from :
这个代码和符号不是我的。Evan K 使用自定义函数解决多值同名查询 ;) 取自:
http://php.net/manual/en/function.parse-str.php#76792Credits go to Evan K.
http://php.net/manual/en/function.parse-str.php#76792致谢 Evan K。
It bears mentioning that the parse_str builtin does NOT process a query string in the CGI standard way, when it comes to duplicate fields. If multiple fields of the same name exist in a query string, every other web processing language would read them into an array, but PHP silently overwrites them:
值得一提的是,当涉及重复字段时,内置的 parse_str 不会以 CGI 标准方式处理查询字符串。如果查询字符串中存在多个同名字段,其他所有 Web 处理语言都会将它们读入数组,但 PHP 会默默地覆盖它们:
<?php
# silently fails to handle multiple values
parse_str('foo=1&foo=2&foo=3');
# the above produces:
$foo = array('foo' => '3');
?>
Instead, PHP uses a non-standards compliant practice of including brackets in fieldnames to achieve the same effect.
<?php
# bizarre php-specific behavior
parse_str('foo[]=1&foo[]=2&foo[]=3');
# the above produces:
$foo = array('foo' => array('1', '2', '3') );
?>
This can be confusing for anyone who's used to the CGI standard, so keep it in mind. As an alternative, I use a "proper" querystring parser function:
<?php
function proper_parse_str($str) {
# result array
$arr = array();
# split on outer delimiter
$pairs = explode('&', $str);
# loop through each pair
foreach ($pairs as $i) {
# split into name and value
list($name,$value) = explode('=', $i, 2);
# if name already exists
if( isset($arr[$name]) ) {
# stick multiple values into an array
if( is_array($arr[$name]) ) {
$arr[$name][] = $value;
}
else {
$arr[$name] = array($arr[$name], $value);
}
}
# otherwise, simply stick it in a scalar
else {
$arr[$name] = $value;
}
}
# return result array
return $arr;
}
$query = proper_parse_str($_SERVER['QUERY_STRING']);
?>
回答by Sjaak Wish
Thanks to @K. Shahzad This helps when you want the rewrited query string without any rewrite additions. Let say you rewrite the /test/?x=y to index.php?q=test&x=y and you want only want the query string.
感谢@K。Shahzad 当您希望重写的查询字符串没有任何重写添加时,这会有所帮助。假设您将 /test/?x=y 重写为 index.php?q=test&x=y 并且您只想要查询字符串。
function get_query_string(){
$arr = explode("?",$_SERVER['REQUEST_URI']);
if (count($arr) == 2){
return "";
}else{
return "?".end($arr)."<br>";
}
}
$query_string = get_query_string();
回答by Kamlesh
Programming Language: PHP
编程语言:PHP
// Inintialize URL to the variable
$url = 'https://www.youtube.com/watch?v=qnMxsGeDz90';
// Use parse_url() function to parse the URL
// and return an associative array which
// contains its various components
$url_components = parse_url($url);
// Use parse_str() function to parse the
// string passed via URL
parse_str($url_components['query'], $params);
// Display result
echo 'v parameter value is '.$params['v'];
This worked for me. I hope, it will also help you :)
这对我有用。我希望,它也能帮助你:)