设置 cookie 时不转义特殊字符
我发现 setcookie() 函数会转义特殊字符,例如引号。我通过清除那些垃圾符号解决了这个问题:
$new_avt = str_replace("\'","",$_COOKIE['avatar']);
$new_avt = str_replace('alt=','',$new_avt);
但我发现这个解决方案很难看。此外,正如您所看到的,我必须删除“alt”属性,因为我无法正确删除其中的转义符号。我想到的唯一其他解决方案是将编码字符串写入 cookie,然后在获取 cookie 时对其进行解码。这个解决方案会比 str_replace() 更快吗?还有更好的方法吗?
感谢您抽出时间。
I've discovered that setcookie() function escapes special characters, such as quotes. I've solved this problem by cleaning out those trash symbols:
$new_avt = str_replace("\'","",$_COOKIE['avatar']);
$new_avt = str_replace('alt=','',$new_avt);
But I find this solution ugly. Furthermore, as you may see, I had to remove 'alt' property, for I couldn't correctly get rid of escape symbol inside it. The only other solution to this I've came up to, is to write an encoded string to cookie, and then decode it when cookie's fetched. Will this solution be faster than str_replace()? Are there any better methods?
Thanks for your time.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您在 cookie 中存储大量数据,那么您可能需要考虑使用会话。这将数据存储在服务器上,而不是在每次请求时将数据发送到客户端或从客户端发送数据。任何可以序列化的变量都可以存储在会话变量中。请参阅http://www.php.net/manual/en/intro.session。 php
If you are storing large amounts of data in cookies, then you might want to consider using sessions instead. This stores the data on the server, rather than sending it to/from the client on each request. Any variable that can be serialized can be stored in a session variable. See http://www.php.net/manual/en/intro.session.php
只需使用 php 函数
stripslashes
即可消除不需要的转义。然后您应该得到与
setcookie()
写入 cookie 的字符串完全相同的字符串。Simply use the php function
stripslashes
to get rid of unwanted escapings.Then you should get exactly the same string as was written into the cookie by
setcookie()
.