PHP URL编码保留无效的url字符 [英] PHP URL encoding retaining invalid url characters

查看:167
本文介绍了PHP URL编码保留无效的url字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将url无效字符替换为url有效,然后再将其转换回来。

I need to replace url invalid characters with something url valid then convert it back again.

这是针对搜索页面的网址,如 http://my.site/search/this-is-a-search ,搜索表单POSTS然后用户重定向到新网址。

This is for a search page with a url like http://my.site/search/this-is-a-search, the search form POSTS then the user redirected to the new url.

Php具有urlencode和urldecode功能,但这些功能根本不起作用,并在我的网址中留下无效字符。

Php has functions urlencode and urldecode however these do not work at all, and leave invalid characters in my url.

当然,我不需要在这里重新发明轮子。

Surely I don't need to reinvent the wheel here.

推荐答案

http://my.site/search/this-is-a-search 这样的东西(即在查询字符串之外),你应该使用 rawurlencode rawurldecode 。这些保证是URL安全的。

For stuff like http://my.site/search/this-is-a-search (i.e., outside the query string), you should use rawurlencode and rawurldecode. These are guaranteed to be URL-safe.

然而, urlencode 也不会生成不安全的URL路径,因为唯一的区别是空格的编码方式和 urlencode 将空格编码为 + ,这在URL路径中是允许的。

However, urlencode will never generate an unsafe URL path either, since the only difference is how spaces are encoded and urlencode encodes spaces to +, which is permitted in the URL path.

来自RFC 1738:

From RFC 1738:


httpurl        = "http://" hostport [ "/" hpath [ "?" search ]]
hpath          = hsegment *[ "/" hsegment ]
hsegment       = *[ uchar | ";" | ":" | "@" | "&" | "=" ]
uchar          = unreserved | escape
unreserved     = alpha | digit | safe | extra
safe           = "$" | "-" | "_" | "." | "+"

这篇关于PHP URL编码保留无效的url字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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