简体   繁体   中英

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

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

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.

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, eg 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM