Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 433
Brooke. Avatar asked Aug 09 '10 05:08

Brooke.


2 Answers

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

like image 200
Haim Evgi Avatar answered Oct 22 '22 10:10

Haim Evgi


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.

like image 25
Borealid Avatar answered Oct 22 '22 09:10

Borealid