转义标题中的特殊字符

In a webpage a user can enter strings into input elements. After the form is submitted, all inputs are verified against rules. After the validation the inpit page is displayed again to the user with marked errors and the already filled in input elements.

Partial code in the validation page for sending back the data:

$query_string = '?filename='.$timed_file_name . '&name=' . $name . '&text='.$text; 
header('Location: http://' . $server_dir . $next_page . $query_string);

It's obvious that the ampersand cannot be used in the header, because if I type jack&jones it will mess up the header and php will return only jack.

I can do it in an ugly way:

Validation page:

$name = html_entity_decode($name); 
$name = str_replace("&","aammppeerrssaanndd",$name);

Input page:

$name = $_GET['name'];
if (strpos($name,'aappoossttrroopphh') !== false) {
    $name = html_entity_decode($name); 
    $name = str_replace("aappoossttrroopphh","&",$name);
}

Is there an easy solution for this?

When creating the URL, run your variables through this:

$var = urlencode( $var );

And when showing users the results, go the other way:

$var = urldecode( $var );

You can use urlencode and urldecode.

In your case, it would used like this:

$query_string = '?filename='. urlencode($timed_file_name) . '&name=' . urlencode($name) . '&text='. urlencode($text);

I think you might want to use http-build-query this makes the query string for you from an array.

The docs say:

Generates a URL-encoded query string from the associative (or indexed) array provided.

Example

$a = array("be"=>"a","wonderful"=>"happier & great","but"=>"strange like @%");
echo http_build_query($a);
//gives "be=a&wonderful= happier +%26+great&but=strange+like+%40%25"

So in your case you would use:

$args = array('filename'=>$timed_file_name, 'name'=>$name, 'text'=>$text);
$query_string = "?".http_build_query($args);