How to handle string to avoid SQL Injection?

Asked

Viewed 1,567 times

3

I have the following code:

$nome = $_POST['nome'];
$ip = preg_replace("/[^a-zA-Z0-9\.]/", "", $_POST['ip']);
$porta = preg_replace("/[^0-9\s]/", "", $_POST['porta']);
$site = preg_replace("/[^a-zA-Z0-9\.]/", "", $_POST['site']);

I’m treating some variables with the exception of one, because she needs to accept accentuation, as I do the treatment of this variable correctly to avoid SQL Injection? And make her accept accents, strokes and brackets?

2 answers

7

It is worth noting that mysql_real_escape_string is OBSOLETE (see in the documentation in English)!

Warning This Extension was deprecated in PHP 5.5.0, and it was Removed in PHP 7.0.0. Instead, the Mysqli or Pdo_mysql Extension should be used. See also Mysql: Choosing an API guide and Related FAQ for more information.

Alternatives to this Function include:

mysqli_real_escape_string()

PDO::quote()

I recommend using PDO or mysqli, always with prepare.

There is already an excellent @rray response on this subject: How to prevent SQL code injection into my PHP code

2


You can use the mysql_real_escape_string (Documentation)

This function will not make you lose unwanted characters, like the way you are farming. They will be encoded so that MYSQL understands them as part of string, and not part of the code.

Browser other questions tagged

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