Reputation: 3017
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?
Upvotes: 3
Views: 1015
Reputation: 115877
You can never be sure that contact
will be a plain string -- it comes from "out there", which automatically makes it unsafe. You should never trust unsafe input, thus parameterized query is the only way to go.
See this article. Granted, it covers an uncommon situation, but it's better to be safe than sorry.
Upvotes: 3
Reputation: 839154
Yes, mysql_real_escape_string
will correctly escape the string so this is safe from SQL injection.
Upvotes: 4
Reputation: 2333
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.
Upvotes: 3
Reputation: 3873
It will not protect you from javascript ; if this string is javascript, and you later display it on a web page, it could be executed.
To be protected from that, you could use htmlentities
.
Upvotes: 1