simple script to prevent SQL injection in PHP

Just a very simple script to prevent SQL injection in PHP. Just add this directly after your database connector is created in your connection file (I assume you just include/require this so it is not written everywhere).

//This stops SQL Injection in POST vars 

foreach ($_POST as $key => $value) {
$_POST[$key] = mysql_real_escape_string($value);

//This stops SQL Injection in GET vars
foreach ($_GET as $key => $value) {
$_GET[$key] = mysql_real_escape_string($value);

Using the logic that $_POST and $_GET are arrays, this simply iterates through each key=>value pair and re-assigns the value as mysql_real_escape_string($value) with the same key. By putting this script straight after your connection, it is only run when safe data is required and is sure to catch and secure all values.


About Cameron
I'm a final year Computer Science/Information Systems major. Already finished my BA in Politics/Philosophy. I do web and software freelance on the side, while I finish studying. Hoping to be self-employed by the end of my degree, otherwise off into the real-world I go....

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

%d bloggers like this: