2010-07-13

Undoing Magic Quotes

by Charles — Categories: PHP — Tags: , , Leave a comment

The often maligned (and rightfully so) magic_quotes_gpc “feature” of PHP can be problematic, especially if you are trying to develop scripts for general consumption on any platform. A brief example of the sort of problem it can cause is that if it is turned on and you do not undo its addition of back-slash escape characters, then if you apply a function such as mysql_real_escape_string() to prepare external data for use in a query, you will end up escaping the magic quotes backslashes and including them in the actual data.

To repair this potential “damage”, my solution is simply to test to see if the feature is turned on, and if it is, to recursively walk through the affected arrays, $_GET, $_POST, $_COOKIE (thus the “gpc”), via the array_walk_recursive() function. My function makes use of an “anonymous function” via the create_function() function. Then all that needs to be done in any script is to run the following function before otherwise using any of those three super-global arrays.

<?php
/**
 * Undo the damage of magic_quotes_gpc if in effect
 * @return bool
 */
function fix_magic_quotes()
{
   if (get_magic_quotes_gpc()) {
      $func = create_function(
         '&$val, $key',
         'if(!is_numeric($val)) {$val = stripslashes($val);}'
      );
      array_walk_recursive($_GET, $func);
      array_walk_recursive($_POST, $func);
      array_walk_recursive($_COOKIE, $func);
   }
   return true;
}

Normal usage would then simply be:

<?php
include 'file/with/this/function.php';
fix_magic_quotes();
/* rest of script... */

Leave a Reply

© 2013 PHP Musings All rights reserved - Wallow theme v0.46.4 by ([][]) TwoBeers - Powered by WordPress - Have fun!