Is ok to urlencode the value in header(Location: value)?

我怕爱的太早我们不能终老 提交于 2019-12-10 16:12:58

问题


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


回答1:


But I do want to urlencode my url because it's made of user provided data

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:

http://www.example.com/rewritten directory/index.php?id=Hello World, how are you?

but you do need to encode rewritten directory and Hello 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.




回答2:


To break the URL up into the "http://" and "the rest" as you've suggested, see PHP's parse_url() and parse_str() functions.

EDIT: this is assuming you know what the querystring parameters will be, e.g param1, param2

$url_parsed = parse_url($url);
$qry_parsed = array();
parse_str($url_parsed['query'], $qry_parsed);
$encurl = "{$url_parsed['scheme']}{$url_parsed['host']}{$url_parsed['path']}?param1=" . urlencode($qry_parsed['param1']) . "&param2=" . urlencode($qry_parsed(['param2'])

header("Location: $encurl");
exit();


来源:https://stackoverflow.com/questions/5085904/is-ok-to-urlencode-the-value-in-headerlocation-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!