如何安全地传递url中的参数

时间:2012-01-09 07:14:55

标签: php cakephp cakephp-1.3 urlencode url-encoding

我正在使用像这个参数的网址

http://localhost/articles/?author=Ben%20Cooper%2CAlex%20Hunter&title=.....&tags=..

我在链接中对它们进行了urlencode。这一切都有效,直到参数中有特殊字符。

例如

http://localhost/articles/?author=..&title=&tags=..

如果,在标题中我有爱&生命,它第一次编码它有爱+%26 +生命,有时它变成Love+%26amp%3B+Life.

为什么会这样?我感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

您需要先使用html_entity_decode()。这会将&(为html而不是网址编码)转换为& 然后 unlencode(),这会将其转换为%26

HTML和URL具有不同的保留字符,编码方式不同。许多框架将自动编码html实体,以帮助防止您的页面奇怪地呈现。想象一下,你在一个字符串中有<,这可能会在页面显示时搞砸页面,因此它会以&lt;的形式回显到html,浏览器会将其呈现为<而不是将其作为标签的一部分。

您无法将&lt;直接编码为%3C< urlencoded),因为它会认为您真的要编码&lt;而不是<这个这就是你需要通过html_entity_decode()

的原因

以下是代码段:

$str = 'Love &amp; Life'; //start with string that may or may not contain htmlentities
$decodedStr = html_entity_decode($str); //replace html entities with their literal counterparts
$urlEncodedStr = urlencode($decodedStr); //urlencode!

希望这有帮助!