Problem
When you build a system that works with a database, this is the biggest concern you should have about the data that is received by the user. For example, when you have a login form where the user passes email and password:
<form method="POST">
Email: <input type="text" name="email" /><br />
Senha: <input type="password" name="senha" /><br />
</form>
And in PHP you get the data this way:
<?php
$login = $_POST["login"];
$senha = $_POST["senha"];
$query = "SELECT * FROM usuarios WHERE login = '{$login}' AND senha = '{$senha}'";
?>
Malicious user wanting to hack into your system can simply type in the fields this ' OR 1 = '1
that the query executed would be:
SELECT * FROM usuarios WHERE login = '' OR 1 = '1' AND senha = '' OR 1 = '1'
Making the query catch the first user it finds and enter the system quietly.
Solution
To escape this type of problem that is common, believe (It is really easy to find systems with this type of failure), it is a good and simple practice to receive the form data this way:
<?php
$login = addslashes($_POST["login"]);
$senha = addslashes($_POST["senha"]);
$query = "SELECT * FROM usuarios WHERE login = '{$login}' AND senha = '{$senha}'";
?>
Where the user when trying to fill in the fields with this ' OR 1 = '1
, would try to run this query:
SELECT * FROM usuarios WHERE login = '\' OR 1 = \'1' AND senha = '\' OR 1 = \'1'
That the database would interpret as 'Take all data of users whose login is equal to ' OR 1 = '1
and password equal to ' OR 1 = '1
.
Running away from the bank attack.
https://xkcd.com/327/
– Ricardo Moraleida
Start here to understand that filters alone are not the solution. You need to sanitize the values according to usage: Using addslashes against SQL injection is safe?.
– Bacco
Thanks for the link, I’m already using the mysqli_real_escape_string direct in DAO methods so can this solve the problem? or I’m forgetting something?
– Reynnan Viktor
Related: Get external variable isset vs filter_input, How to validate each data type received from a form? and How to prevent SQL code injection into my PHP code
– rray