PHP Tutorial: Easy SQL Injection Prevention

Leave a comment Standard

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);
        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

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s