Quick and easy $_POST security…

By , Thursday 25th October 2007 7:44 pm

Please ignore this post, quite frankly its old and there’s much better ways to do stuff than this.

A quick and easy way to protect yourself from mySQL injection attacks in PHP is to use…

$sql = "insert into table set ";
 foreach ($_POST as $key => $data)
 {
     $sql .= $key." = '".strip_tags(htmlentities(addslashes($data)))."',";
 }
 $sql .= mysql_query(rtrim($sql,',').";") or die(mysql_error());

What this script does is to take your $_POST data and remove anything malicious from it. Looping over the $_POST data we build up an SQL statement. At the end then we simply execute using with mysql_query.

NOTE: This does not validate your data, it just helps prevent malicious attacks.

Another version of this that I use to to grab all my form information into variables to to place the following code within the foreach loop instead…

eval("$".$key." = '".strip_tags(htmlentities(addslashes($data)))."';");

This makes up a list of variables following your forms field names and strips malicious code from them. This method then allows you to do some form validation before inserting data into your tables ;)

Liked this post? Follow this blog to get more. 

Leave a Reply

You must be logged in to post a comment.

Panorama Theme by Themocracy

1 visitors online now
0 guests, 1 bots, 0 members
Max visitors today: 6 at 03:27 am UTC
This month: 15 at 10-10-2017 02:55 pm UTC
This year: 45 at 02-01-2017 10:28 pm UTC
All time: 130 at 28-03-2011 10:40 pm UTC