PHP sanitize user data for use in header() function PHP sanitize user data for use in header() function php php

PHP sanitize user data for use in header() function


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.


There could be some exploits used there, like multiple headers sent, despite the fact that if you are running PHP5.1 this is prevented by PHP it selfs are reported here:

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

A part from that, if you are expecting a query string to be attached to that file and you are not using SEO urls you should validate the query string with urlencode() which will check whatever the string is a query string or not and will replace strange chars or not allowed chars with appropriate % and +.

References:


You can also use http_build_query to convert an associated array into the query string.

<?php    $data = array('foo'=>'bar',          'baz'=>'boom',          'cow'=>'milk',          'php'=>'hypertext processor');    echo http_build_query($data) . "\n";?>

The above example will output:

foo=bar&baz=boom&cow=milk&php=hypertext+processor