如何在HTML中对href属性进行编码 [英] how to encode href attribute in HTML

查看:178
本文介绍了如何在HTML中对href属性进行编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于href属性的内容应该做些什么:HTML或URL编码?

 < a href =?? ?>链接文字< / a> 

一方面,由于href属性包含URL,所以我应该使用URL编码。
另一方面,我将这个URL插入到HTML中,所以它必须是HTML编码的。



请帮我解决这个矛盾。 p>

谢谢。






编辑:

这是矛盾。假设URL中可能有'&'和'>'字符。 URL编码不会转义它们,因此href属性中会有保留的HTML字符,这违反了标准。 HTML编码将会转义'&'和'>'字符,并且HTML将是有效的,但在此之后,URL中将会有意外的'&'字符(这是URL的保留字符,它被用作查询字符串的分隔符参数)。



保留的URL字符 a>构成了保留的HTML字符的超集,除了<'和'> '保留为HTML但不包含URL。






编辑2:



我错了'&'和'>'字符,它们实际上是通过URL编码转义的。如果是这样,在这种情况下URL编码就足够了,是不是? 解决方案

正常构建URL。遵循构建URL的规则。对输入的数据进行编码。

然后像平常一样构建HTML。遵循构建HTML的规则。对数据进行编码。

即做两个(但按正确的顺序)。



它们不是相互排斥的,所以没有矛盾。



例如(这是一个简化的例子,假设$ _GET中的数据是正确的并且存在,不要在真实世界中这样做):

  $ search_term = $ _GET ['q']; 
$ page = $ _GET ['page'];
$ next_page = $ page + 1;
$ next_page_url ='http://example.com/search?q='。 urlencode($ search_term)。 '& page ='。进行urlencode($页);
$ html ='< a href ='。htmlspecialchars($ next_page_url)。'>链接文字< / a>';


What should be done against contents of href attribute: HTML or URL encoding?

<a href="???">link text</a>

On the one hand, since href attribute contains URL I should use URL encoding. On the other hand, I'm inserting this URL into HTML, so it must be HTML encoded.

Please help me to overcome this contradiction.

Thanks.


EDIT:

Here's the contradiction. Suppose there might be the '<' and '>' characters in the URL. URL encoding won't escape them, so there will be reserved HTML characters inside the href attribute, which violates the standard. HTML encoding will escape '<' and '>' characters and HTML will be valid, but after that there will be unexpected '&' characters in the URL (this is reserved character for URL, it's used as a delimiter of query string parameters).

Reserved URL characters forms a superset of reserved HTML characters except for the '<' and '>' that are reserved for HTML but not for URL.


EDIT 2:

I was wrong about '<' and '>' characters, they are actually percent escaped by URL encoding. If so, URL encoding is sufficient in this case, isn't it?

解决方案

Construct a URL as normal. Follow the rules for constructing URLs. Encode data you put into it.

Then construct HTML as normal. Follow the rules for constructing HTML. Encode data as you put it into it.

i.e. Do both (but in the right order).

They aren't mutually exclusive, so there is no contradiction.

For example (this is a simplified example that assumes data in $_GET is correct and exists, don't do that in the real world):

$search_term = $_GET['q'];
$page = $_GET['page'];
$next_page = $page + 1;
$next_page_url = 'http://example.com/search?q=' . urlencode($search_term) . '&page=' . urlencode($page);
$html = '<a href="' . htmlspecialchars($next_page_url) . '">link text</a>';

这篇关于如何在HTML中对href属性进行编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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