Good for urlencode 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 am redirected to some strange place like $ url / $ url which gives me 404 of course.

But I want urlencode my url because it is made from user provided data. How can I do it? Can I break it with "http: //" and "rest" and only urlencode "rest"?

What is the recommended practice in this situation?

thanks

+4
source share
2 answers

But I want urlencode my url because it made the data provided by the user

The solution does not encode the full URL; it encodes only bits that require encoding. Simple coding "the rest" will also fail. For example, in this example, all the dashes ? and = must remain unchanged:

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

but you need to code the rewritten directory and Hello World, how are you? so that all this forms a valid URL.

As with character encodings, you need to make sure that it is encoded from the very beginning. The solution to your problem (if it exists at all - header() will most likely work without urlencode () in the first place!), Most likely, it will be further in your code.

+5
source

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

EDIT:, it is assumed that you know what the query parameters will be like 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(); 
+2
source

Source: https://habr.com/ru/post/1340894/


All Articles