php 使用 & 在 URL 错误了 $_GET
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6322562/
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
Using & in URL bugs up the $_GET
提问by Steven
Running my site through http://validator.w3.org/check, I get a lot of error messages saying that my links should use &
in stead of &
.
通过运行我的网站http://validator.w3.org/check,我得到了很多错误信息,说我的链接应该用&
在代替&
。
So I updated my code, only to find out that $_GET
does not like this.
所以我更新了我的代码,才发现$_GET
不喜欢这样。
My URL was this: www.mysite.com/?foo=1&bar=2
and I changed it to this: www.mysite.com/?foo=1&bar=2
我的网址是这样的:www.mysite.com/?foo=1&bar=2
我把它改成了这样:www.mysite.com/?foo=1&bar=2
The problem is that doing a print_r($_REQUEST)
gives me this result:
问题是做 aprint_r($_REQUEST)
给了我这个结果:
Array ( [foo] => 1 [amp;storeid] => 2 )
Why doesn't $_GET
, $_POST
and $_REQUEST
recognize the &
?
为什么不$_GET
,$_POST
并$_REQUEST
识别&
?
UPDATE
This is one of the ways I generate a URL:
更新
这是我生成 URL 的方法之一:
$url = get_bloginfo('url')."/?foo=".$element['name']."&bar=".$element['id'];
$link = '<a href="'.$url.'" title="'.$element['name'].'">'.$element['name'].'</a>';
回答by phihag
&
is the HTML entity reference for &
. URL parameters are still separated by a single &
, but if you mention the URL in HTML, you need to encode it. For
&
是 的 HTML 实体引用&
。URL 参数仍然由单个 分隔&
,但如果您在 HTML 中提及 URL,则需要对其进行编码。为了
<img src="img?width=100&height=100" />
the browser then requests img?width=100&height=100
.
然后浏览器请求img?width=100&height=100
.
回答by Lightness Races in Orbit
You must be double-encoding somewhere, such that your link:
您必须在某处进行双重编码,以便您的链接:
www.mysite.com/?foo=1&bar=2
becomes:
变成:
www.mysite.com/?foo=1&bar=2
and then:
进而:
www.mysite.com/?foo=1&amp;bar=2
What you read is correct. To clarify, in your HTML&
must be encoded as &
. Of course the URL itself still just contains &
; PHP never sees "&
" because that encoding is for the benefit of your browser.
你读的是正确的。澄清一下,在您的 HTML 中&
必须编码为&
. 当然,URL 本身仍然只包含&
; PHP 永远不会看到“ &
”,因为该编码是为了您的浏览器的利益。
回答by Marek Dajnowski
// Fix for & bug in url
if( $_GET ) foreach( $_GET as $key => $value )
{
if( strpos( $key, 'amp;' ) === 0 )
{
$new_key = str_replace( 'amp;', '', $key );
$_GET[ $new_key ] = $value;
unset( $_GET[ $key ] );
}
}
It won't work with filter_input :(
它不适用于 filter_input :(
回答by Karolis
In any case it's not a good practice to encode various URL parts by hands. You should do like this:
在任何情况下,手动编码各种 URL 部分都不是一个好习惯。你应该这样做:
$query_string = 'foo=' . urlencode($element['name']) . '&bar=' . urlencode($element['id']);
echo '<a href="mycgi?' . htmlspecialchars($query_string) . '">';
I think this will solve unneeded problems.
我认为这将解决不必要的问题。