&符号是否应该在查询字符串中进行 URL 编码? [英] Should an ampersand be URL encoded in a query string?

查看:40
本文介绍了&符号是否应该在查询字符串中进行 URL 编码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我经常看到这个网址出现.

https://ghbtns.com/github-btn.html?user=example&repo=card&type=watch&count=true

&& 还是应该/可以保留为 &?

解决方案

来自 rfc3986:

<块引用>

保留字符
URI 包括由保留"集中的字符分隔的组件和子组件.这些字符被称为保留",因为它们可能(也可能不)被通用语法、每个特定于方案的语法或由 URI 的解引用算法的特定于实现的语法定义为定界符.
...

 reserved = gen-delims/sub-delimsgen-delims = ":"/"/"/"?"/"#"/"["/"]"/"@"子delims =!"/"$"/"&"/"'"/"("/")"/"*"/"+"/","/";"/"="

<块引用>

保留字符的目的是提供一组定界符可与 URI 中的其他数据区分开来的字符.URI不同之处在于将保留字符替换为其相应的百分比编码八位字节是不等价的.对保留字符进行百分比编码,或对百分比编码进行解码对应于保留字符的八位字节,将改变大多数应用程序都会解释 URI.
...
URI 生成应用程序应该对数据八位字节进行百分比编码对应于保留集中的字符,除非这些字符URI 方案特别允许在其中表示数据成分.如果在 URI 组件中找到保留字符并且没有定界作用该字符已知,那么它必须是解释为表示对应的数据八位字节US-ASCII 中的字符编码.

因此,如果 URL 中的 & 是值的一部分并且没有分隔角色,则应该对其进行编码.
这是使用 的简单 PHP 代码片段urlencode() 函数:

';?>

For example I quite often see this URL come up.

https://ghbtns.com/github-btn.html?user=example&repo=card&type=watch&count=true

Is the & meant to be &amp; or should/can it be left as &?

解决方案

From rfc3986:

Reserved Characters
URIs include components and subcomponents that are delimited by characters in the "reserved" set. These characters are called "reserved" because they may (or may not) be defined as delimiters by the generic syntax, by each scheme-specific syntax, or by the implementation-specific syntax of a URI's dereferencing algorithm.
...

  reserved    = gen-delims / sub-delims

  gen-delims  = ":" / "/" / "?" / "#" / "[" / "]" / "@"

  sub-delims  = "!" / "$" / "&" / "'" / "(" / ")"
              / "*" / "+" / "," / ";" / "="

The purpose of reserved characters is to provide a set of delimiting characters that are distinguishable from other data within a URI. URIs that differ in the replacement of a reserved character with its corresponding percent-encoded octet are not equivalent. Percent-encoding a reserved character, or decoding a percent-encoded octet that corresponds to a reserved character, will change how the URI is interpreted by most applications.
...
URI producing applications should percent-encode data octets that correspond to characters in the reserved set unless these characters are specifically allowed by the URI scheme to represent data in that component. If a reserved character is found in a URI component and no delimiting role is known for that character, then it must be interpreted as representing the data octet corresponding to that character's encoding in US-ASCII.

So & within a URL should be encoded if it's part of the value and has no delimiting role.
Here's simple PHP code fragment using urlencode() function:

<?php
    $query_string = 'foo=' . urlencode($foo) . '&bar=' . urlencode($bar);
    echo '<a href="mycgi?' . htmlentities($query_string) . '">';
?> 

这篇关于&符号是否应该在查询字符串中进行 URL 编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆