Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP sanitize user data for use in header() function

Are there any escape routines that need to be done to user data for it to be used inside PHP's header() function?
Eg for MySQL I run mysql_real_escape_string() over user data before sending it to the DB and for output in HTML I run htmlspecialchars()... both wrapped in my own custom function to do some other processing first.

But for PHP's header() function, what needs to be done? Are there any dangerous characters that I should escape?

I'm trying to do something like this... appending the query string to a header() redirect to a different page

if ( strlen($_SERVER['QUERY_STRING']) > 0) {
$query_string = '?'.$_SERVER['QUERY_STRING'];
}
header('Location: http://domain.com/activate.php'.$query_string);
exit();

Anyone got any info on what needs to be escaped for the header() function? Colon and semi-colon characters always seem pretty critical to header() statements. Should I escape those?

like image 821
batfastad Avatar asked Apr 15 '11 13:04

batfastad


People also ask

What PHP can do with header () function?

The header() function is an predefined PHP native function. With header() HTTP functions we can control data sent to the client or browser by the Web server before some other output has been sent. The header function sets the headers for an HTTP Response given by the server.

What does the function header sent in PHP return?

The headers_sent() function will put the PHP source file name and line number where output started in the file and line variables if the file and line parameters are set. Return Value: This function returns True if headers has been sent and false otherwise.


1 Answers

No, there is nothing that you need to do to protect yourself as long as you're using PHP >= 4.4.2 (if on PHP4) and >= 5.1.2 (if PHP5).

See the docs for header(). Specifically:

This function now prevents more than one header to be sent at once as a protection against header injection attacks.

So there's no significant need to escape anything for a Location Header. If you're on earlier versions, you'd need to escape all \r and \n characters (to prevent header injection).

Also, don't urlencode the query string. It will break the semantic meaning of the data being sent. Just append it in full.

like image 112
ircmaxell Avatar answered Oct 16 '22 08:10

ircmaxell