I normally use this function to sanitize my form inputs before storing them into my database:
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = @trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
Until today I didn't realize that mysql_real_escape_string
required a database connection as I've only used it when I've been cleaning the data before storing it into the database.
I tried using the function on a contact form and got the "A link to the server could not be established" error. I could connect to the database but there is no need because I simply am trying to sanitize the data before it's being sent out to my e-mail via the contact form.
What is the best way to sanitize data that's not being stored in a mysql database and does this data still need to be sanitized?
use filter_var()
http://php.net/manual/en/function.filter-var.php
like if you want to sanitize an email:
$_POST['email'] = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
to message
$_POST['message'] = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
is enogth
The purpose of sanitizing the data with mysql_real_escape_string
is to avoid SQL injection. If you're not using SQL, you're already immune.
Men don't get cervical cancer.
Use a sanitization function appropriate to the special characters you need to avoid. Ideally, don't strip something which won't cause harm.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With