Why are $_POST variables getting escaped in PHP?

Solution 1:

You probably have magic quotes enabled on the Linux server: magic_quotes

When magic_quotes are on, all ' (single-quote), " (double quote), \ (backslash) and NUL's are escaped with a backslash automatically.

They're a good thing to disable, as they are going to be removed from PHP 6 onwards anyway. You should also be able to disable them inside your script: set-magic-quotes-runtime You can't deactivate the part of magic_quotes responsible for escaping POST data during runtime. If you can, disable it in php.ini. If you can't do that, do a check whether the magic_quotes are enabled, and do a stripslashes() on any content you fetch from POST:

if (get_magic_quotes_gpc())  
 $my_post_var = stripslashes($_POST["my_post_var"]);

Solution 2:

I don't think this applies in your case, but I was just having a similar problem. I was loading a WordPress install along with a site, so I could show recent posts on all pages. It turns out WordPress escapes all $_POST vars, no matter what magic_quotes are set to.

I mention it because it was frustrating to figure out, and googling for an answer brought me here.

Here's how I fixed it in my case:

$temp_POST = $_POST;
require '../www/wp_dir/wp-load.php'; // Loading WordPress
$_POST = $temp_POST;

Solution 3:

This is a PHP "feature" known as Magic Quotes, which has now been deprecated in PHP 5.3 and removed in PHP 5.4.

It is easy to disable the silly nuisance in php.ini.

Solution 4:

You likely have magic quotes turned on in your production environment. Inspect phpinfo() output.

You can run all of your inputs through something like this to strip the quotes:

        /* strip slashes from the string if magic quotes are on */
    static function strip_magic_slashes($str)
    {
            return get_magic_quotes_gpc() ? stripslashes($str) : $str;
    }