Cleaning Variables From User Input Forms in PHP

Cleaning user input data for MySQL queries is pretty important. In PHP, most people will do mysql_real_escape_string($_POST['myVar']) to clean the data. This is okay if you have few user variables coming in. However, what if you have an application that has hundreds of fields that may change? You will have to go in and modify a long set of mysql_real_escape_string()s in order to make sure things are clean. There is a neat little function called array_map() that can make life so much easier. So below is a easy function to have around to clean your user variables. Just pass it your $_POST or $_GET arrays.

function clean_array($post)
{
  // magic quotes can cause problems 
  if(get_magic_quotes_gpc())
   {
        $_POST = array_map("stripslashes", $post);
   }

   return array_map("mysql_real_escape_string", $post);
}

Now when you want to work with user data just do the following:

$post_arr = clean_array($_POST);
$get_arr = clean_array($_GET);

I can't believe it took me so long to figure this out. Every once in a while, I would just get frustrated with cleaning user input and would Google for a solution. Apparently, I just didn't know what search terms to use.