dontknow
dontknow

Reputation: 89

mysqli_real_escape_string vs filter_input()? What method should I use?

I don't know when to use each one of them.

$name = mysqli_real_escape_string($connection, $_POST['name']); 

or

$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);

Upvotes: 0

Views: 1794

Answers (1)

urfusion
urfusion

Reputation: 5501

real_escape_string() have to be used for the sql strings, i.e. parts of the query enclosed in quotes. Have to be used unconditionally, despite of whatever previous manipulations. real_escape_string() Escapes special characters in a string for use in an SQL statement, taking into account the current char set of the connection.

Where as

filter_input Gets a specific external variable by name and optionally filters it. filter_input will provide you way to validate input for specific string and characters.

  1. Validate filters
  2. Sanitize filters
  3. Other filters
  4. Filter flags

Validate filters

As name suggested it is use for validation for specific input like FILTER_VALIDATE_EMAIL.

$email = "abc@example"; // wrong email

if(filter_var($email, FILTER_VALIDATE_EMAIL)){
    echo $email.'<br>';
    var_dump(filter_var($email, FILTER_VALIDATE_EMAIL));
}else{
    var_dump(filter_var($email, FILTER_VALIDATE_EMAIL));   
} 

Sanitize filters it will use for validate and remove characters from string.

FILTER_SANITIZE_EMAIL   "email"         Remove all characters except letters, digits and !#$%&'*+-=?^_`{|}~@.[]. 

For more information on filter_value.

So I think that both have different roles to play.

Upvotes: 1

Related Questions