php $_POST with special characters


I just wondered why $private_key=$_POST['pkey']; doesn´t work, when I use a variable with AJAX, which also contains a +.

The solution is surprisingly simple: PHP changes fields containing the characters space, dot and others to ensure compatibility with the (obsolete) register_globals.

There are many workarounds. I use this function:

function getRealPOST() {
    $pairs = explode("&", file_get_contents("php://input"));
    $vars = array();
    foreach ($pairs as $pair) {
        $nv = explode("=", $pair);
        $name = urldecode($nv[0]);
        $value = urldecode($nv[1]);
        $vars[$name] = $value;
    }
    return $vars;
}

Many thanks for publishing this function to stackoverflow.com.

But if the passed variable contains one or more = this no longer works because of $nv = explode("=", $pair);. In this case explode must be limited to two fields: $nv = explode("=", $pair, 2);

Leave a comment

Your email address will not be published. Required fields are marked *