How best to avoid sql inject

Asked

Viewed 206 times

1

Well I have 2 ways to prevent sql inject, are they:

first

$input = $conexao->real_escape_string($input);

2nd

$input = filter_var ($input, FILTER_SANITIZE_SPECIAL_CHARS);

Query

select * from cadastro where nome = '".$input."' LIMIT 1

What is the best way?

The real_escape_string requires mysql or php server resource?

  • more here https://wiki.locaweb.com.br/pt-br/Como_se_proteger_do_SQL_Injection

  • 2

    The FILTER_SANITIZE_SPECIAL_CHARS for me is terrible. It will convert other information like the <, > and even the &. In my opinion the database should store all the original content and use the htmlentites (or htmlspecialchars) in the output of the information, never in the input. Also, if using the FILTER_SANITIZE_SPECIAL_CHARS you will spend a < for &lt;, then you’ll make a json_encode of a value &lt;, doesn’t make any sense. Imagine that my username is<dev>, you will get the information from &lt;dev&lr;. About "consuming resources", everything consumes. :)

1 answer

2

Using PDO also helps

 $query = "SELECT* FROM cadastro WHERE nome = :nome LIMIT 1";

 $stmt = $this->connection->prepare($query);
 $stmt->bindValue(":nome", $input, PDO::PARAM_STR);

Thus, you define what type of variable goes for each parameter PDO::PARAM_STR

Browser other questions tagged

You are not signed in. Login or sign up in order to post.