Pop-unders »
« Validating domains and email addresses 
Posted: June 8th, 2008 @ 09:08pm

Where are these backslashes coming from?

Are you seeing backslashes (\) being inserted before quotes in the data you’re using? Have you “solved” the problem using stripslashes? Do you want to know where these are coming from and how to stop it? Of course you do… read on!

What’s causing it?

There is a configuration option called magic_quotes_gpc that is, for historic reasons, on by default. It’s this option that’s causing the backslashes. It effectively runs the addslashes function on all GET, POST and COOKIE data.

The reason for this is that many years ago this was the recommended way to escape incoming data before sending it to a SQL database. Having it done automatically could be seen to be useful. Personally I hate it - I’d rather know what’s happening to the data I’m dealing with and not rely on the server being configured in a certain way.

How do I stop it?

The simple answer is to turn magic_quotes_gpc off. Unfortunately not everyone has the luxury of being able to do that so the following chunk of code can be placed at the top of any file to check for and undo the addslashes on the GET, POST and COOKIE superglobals. This is pretty-much required to write run-anywhere PHP scripts.

if (get_magic_quotes_gpc()) {
  function stripslashes_array($array) {
    return  is_array($array)
           ?
            array_map('stripslashes_array', $array)
           :
            stripslashes($array);
  }  

  $_COOKIE = stripslashes_array($_COOKIE);
  $_FILES = stripslashes_array($_FILES);
  $_GET = stripslashes_array($_GET);
  $_POST = stripslashes_array($_POST);
  $_REQUEST = stripslashes_array($_REQUEST);
}

Rather than placing this in every file I’d recommend putting it in a separate file that you include at the top of each file. Alternatively you could use the auto_prepend_file php.ini directive to include it for all scripts.

Tags:

2 Responses to “Where are these backslashes coming from?”


  1. Aaron Saray said...

    I think it might be useful to your readers to point out the reason why you created this function in this particular way instead of using the array_walk_recursive function. My first thought was that - but you’ll notice how it won’t handle keys with the contents of arrays :)

    Also, one wonders - could you find a test for using ini_set() on magic quotes first?


  2. Stut said...

    Thanks Aaron, you’re quite correct. Also worth noting that array_walk_recursive is not available in PHP4.

    As far as I know changing magic_quotes_gpc in code will not affect the global arrays since they’ve already been processed.

Leave a Reply

The Stut.net blog is proudly powered by WordPress | Entries (RSS) and Comments (RSS)
Generated in 0.6225 seconds. All content copyright © Stuart Dallas unless otherwise stated.
Design and content licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 2.0 License