WordPress: Auto adds slashes to $_POST, $_GET, $_REQUEST, $_COOKIE

When I first hard coded a form into a WordPress page and print_r() the results, all the quotes were escaped. Now, being a reasonably savvy developer at times, my first thought was obviously, “Oh the server must have magic quotes turned on”. So I did my due diligence and checked, but oddly it didn’t. After a lot of googling it turns out that the WordPress core automatically adds slashes to all input arrays. “Why, oh god why” you rightly ask. Well the answer is simple, WordPress has been around a long time now and has to run on a variety of different servers all with different settings. To maintain consistency and provide the best possible security they decided to force adding slashes to all input, even if the server had magic_quotes turned off, ensuring that consistency is maintained across the core code.

Why would you ever want magic quotes and what does it do?

Magic Quotes were added to PHP very early on as a one size fits all approach to help beginners write better and more secure code. What it does is automatically add slashes () to single and double quotes in any possible user facing data array, ($_POST, $_GET, $_REQUEST, $_COOKIE). Adding slashes to any data going near a database helps prevent SQL injection and makes database interaction much safer and is generally a good thing. However, PHP automatically adding slashes to data arrays has caused no end of headaches for developers over the years, namely because you often need to manipulate the data before it goes anywhere near a database, if it ever does. Most servers these days have magic quotes disabled, indeed, it’s been depreciated in PHP since 5.3.0 and will be actively removed, 5.4.0. You can read more about magic quotes on the official PHP site here.

Ok, how do I to fix it in WordPress

WordPress realises you might not want slashes automatically added and so provides a nice function called stripslashes_deep that enables you to remove them should you wish. WARNING: As mentioned above, the WordPress core relies on the all code being escaped, (in particular $_REQUEST), so don’t remove it early on in the page execution, only later after all the initial core stuff has loaded and you want to process the data.

Either way, you can use array_map with the native WordPress stripslashes_deep function to remove all the added slashes. Use the code below to do just that.


$_POST = array_map( 'stripslashes_deep', $_POST );
$_GET = array_map( 'stripslashes_deep', $_GET );
$_COOKIE = array_map( 'stripslashes_deep', $_COOKIE );
$_REQUEST = array_map( 'stripslashes_deep', $_REQUEST );