How to Filter $_POST variable against MySQL injection?


One of the main weakness in PHP scripts particularly for amateur programmers is the lack of validation particularly when handling PHP driven forms. Below is a vulnerable script for MySQL injection:

<?php
if (!isset($_POST['email']) || trim($_POST['email']) == "")
{
die ('ERROR: Enter email');
}
else
{
$email =$_POST['email'];
?>

$_POST is not filtered for any unwanted form inputs. Hackers commonly exploit this for MySQL injection attacks. So a more secure script should be:

<?php
if (!isset($_POST['email']) || trim($_POST['email']) == "")
{
die ('ERROR: Enter email');
}
else
{
$email =$_POST['email'];
//sanitize for illegal characters
$email = mysql_real_escape_string(stripslashes($email));
?>

If you are interested in advanced PHP form validation. Check out this DevShed tutorial: Advanced PHP form input validation



Related posts: