I have the following code that adds a record to my MySQL database via PHP: Contact is just a plain string.

$contact = mysql_real_escape_string(stripslashes($_POST["contact"]), $con); 
$sql="INSERT INTO custom_downloads (contact) VALUES ('$contact')";

Is this good enough to prevent any sort of SQL injection attacks? What else can I do to cleanse the data?


Not "this line" but these lines. quotes around $contact variable in the second line is no less important than mysql_real_escape_string in the first one

Written by Col. Shrapnel

too bad you have chosen the worst answer.

Written by Col. Shrapnel

Accepted Answer

bluebit, your code is secure with regard that you're protecting against SQL Injection but you're not secure against things like XSS (Cross Site Scripting). This is the ability to pass Javascript into this field and then when you output it, you're outputting the Javascript.

To avoid this you can run your input through strip_tags() www.php.net/strip_tags this will remove all HTML tags from your input, thus getting rid of

Here is a nice function that you can reuse for all inputs you're receiveing from $_POST and wish to secure

$cleanInput = cleanPost($_POST['contact']);

function cleanPost($item) {
    return mysql_real_escape_string(strip_tags(stripslashes($item)));

There is also a built-in function in PHP for handling input types called filter_var() This allows you to specify wether you want to remove HTML and such, just like strip_tags()

Hopet this you realise you need to protect against SQL Injection and XSS.

Written by Paul Dragoonis
This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the stackoverflow.com community.
It is licensed under cc-wiki