Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Strip slashes from user input (if applicable) (See related posts)

This code checks if magic quotes are enabled, and if so, strips slashes from GET, POST and COOKIE arrays. It's fully recursive, and thus supports POST arrays.

   1  <?php
   2  
   3  // If magic quotes are enabled, strip slashes from all user data
   4  function stripslashes_recursive($var) {
   5  	return (is_array($var) ? array_map('stripslashes_recursive', $var) : stripslashes($var));
   6  }
   7  
   8  if (get_magic_quotes_gpc()) {
   9  	$_GET = stripslashes_recursive($_GET);
  10  	$_POST = stripslashes_recursive($_POST);
  11  	$_COOKIE = stripslashes_recursive($_COOKIE);
  12  }
  13  
  14  ?>

Comments on this post

mattm posts on May 25, 2005 at 14:39
you do realize that since it's recursive, you can just do this:

   1  
   2  if (get_magic_quotes_gpc()) {
   3      $_GET = stripslashes_recursive($_GET);
   4      $_POST = stripslashes_recursive($_POST);
   5      $_COOKIE = stripslashes_recursive($_COOKIE);
   6  }
XoloX posts on May 27, 2005 at 00:32
Eh... Yeah! Right! Of course

(thanks :)
PeterOdding posts on Aug 20, 2008 at 18:43
OK so I lost the password to my "xolox" account here and I can't seem to find a way to reset my old account. The point is I recently learned that the above recursive function can be used to bring your server down! For an explanation see http://talks.php.net/show/php-best-practices/26 but in short, replace the above with the following:

   1  
   2  <?php
   3  
   4  if (get_magic_quotes_gpc()) {
   5   $in = array(&$_GET, &$_POST, &$_COOKIE);
   6   while (list($k,$v) = each($in)) {
   7    foreach ($v as $key => $val) {
   8     if (!is_array($val)) {
   9      $in[$k][$key] = stripslashes($val);
  10      continue;
  11     }
  12     $in[] =& $in[$k][$key];
  13    }
  14   }
  15   unset($in);
  16  }
  17  
  18  ?> 

You need to create an account or log in to post comments to this site.


Click here to browse all 5551 code snippets

Related Posts