lang="en-US"> PHP Tutorial: Easy SQL Injection Prevention –  Design1online.com, LLC

PHP Tutorial: Easy SQL Injection Prevention

I’ve noticed on several client games I’ve worked on recently that instead of creating a global cleaning function to prevent SQL injections they’re wrapping mysql_real_escape_string() calls around everything. Sure, putting this function around any variable retrieving data from a form is okay — but it also leaves you open to forgetting or overlooking one. Below is a function you can run before trying to access $_GET and $_POST data. I typically put it in a header include file and run it before I do anything else on the page. It automatically cleans $_GET and $_POST so you can use it without worrying about SQL injections.

/*******
* Prevent SQL Injections
* Walk through the value and call mysql_real_escape_string on all values
*******/
function preventInjections($value)
{
    if (is_array($value))
        return array_map('preventInjections',$value);
    else
        return mysql_real_escape_string(trim($value));
}

/*******
* Run this at the top of every page before you try to use
* anything from your $_GET or $_POST variables
*******/
if (!get_magic_quotes_gpc())
{
    $_POST = preventInjections($_POST);
    $_GET = preventInjections($_GET);
}

/*******
* From this point on you can use your $_GET and $_POST variables 
* like you normally would without fear of injections
*******/
print_r($_POST);
print_r($_GET);

You may also like...

Leave a Reply