可以对 header(Location: value) 中的值进行 urlencode 吗?
这是PHP。
我做得很好
header("Location: " . $url)
并且工作得很好。但如果我这么做了,
header("Location: " . urlencode($url))
我会被重定向到一些奇怪的地方,比如 $url/$url ,这当然会给我一个 404 错误。
但我确实想对我的网址进行 urlencode,因为它是由用户提供的数据组成的。我该怎么做呢?我可以将其分解为“http://”和“其余部分”并且仅对“其余部分”进行urlencode吗?
在这种情况下,建议采取哪种做法?
谢谢
This is PHP.
I do
header("Location: " . $url)
and works great. But If I do
header("Location: " . urlencode($url))
I'm redirected to some weird place like $url/$url which gives me a 404, of course.
But I do want to urlencode my url because it's made of user provided data. How can I do it? Can i break it un "http://" and "the rest" and only urlencode "the rest"?
Which is the recommended practice in this situation?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
解决方案是不要对完整的 URL 进行编码,只对需要编码的位进行编码。仅仅对“其余部分”进行编码也必然会失败。例如,在此示例中,所有斜杠、
?
和=
必须保持不变:但您确实需要对
重写目录
和进行编码>你好,世界,你好吗?
为了使整个事情形成一个有效的 URL。
与字符编码一样,您需要从一开始就确保知道什么是如何编码的。您的问题的解决方案(如果有的话 -
header()
很可能首先不需要 urlencode() 就可以工作!)可能会在您的代码中更靠前。The solution is don't encode the full URL, encode only the bits that need encoding. Just encoding "the rest" is bound to fail as well. In this example for example, all slashes, the
?
and the=
must stay intact:but you do need to encode
rewritten directory
andHello World, how are you?
in order for the whole thing to form a valid URL.
Like with character encodings, you need to make sure from the start to know what is encoded how. The solution to your problem (if there is one at all -
header()
is likely to work without urlencode() in the first place!) is likely to be further up in your code.要按照您的建议将 URL 分解为“http://”和“其余部分”,请参阅 PHP 的
parse_url()
和parse_str()
函数。编辑:假设您知道查询字符串参数是什么,例如
param1,param2
To break the URL up into the "http://" and "the rest" as you've suggested, see PHP's
parse_url()
andparse_str()
functions.EDIT: this is assuming you know what the querystring parameters will be, e.g
param1, param2