BandonRandon BandonRandon - 1 year ago 79
PHP Question

Sanitize contact form without mysql_real_escape_string

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
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?

Answer Source

use filter_var()

a great tutorial :

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download