I want the example of why substituting 'by' and '\' for parameters to a query is dangerous

0

I see many posts on this subject, but I do not see any examples that fit in my case.

function sanitize($value)
{
    $val = str_replace("'", "''", $value);
    $val = str_replace("\", "\\", $val);

    return $val;
}

The query would be mysqli_query($conn,"insert into tabela (Nome) values ('".sanitize($ipt)."')") Considering that even int will go into this procedure above and considering that all queries will be written EXACTLY in this way, with parameters marked with '(single quotes), what input would be able to break security and cause an injection?

    
asked by anonymous 25.07.2016 / 23:22

1 answer

2

In your example the insert is actually escaping the characters in order to avoid injection. Okay.

The big problem is the way you do it:

  

Considering that even int will enter this procedure above and   considering that all queries will be written EXACTLY from this   way [...]

How will you ensure this with extreme certainty? If you forget sanitize in a single query , how will you figure it out? Just one place and your site is vulnerable.

If something has a chance to go wrong, it will go wrong ... So why give chance a chance?

If the language offers ways to avoid such problems natively, what is the problem with using this solution?

We have the prepared statments in the mysqli , in the PDO , where the sanitize of the query is done in an assertive and transparent way that becomes incoherent not to use them if it knows about its existence .

Keeping the code is also simpler. Here's an example:

$connection = new PDO('mysql:dbname=test;host=127.0.0.1', 'db', 'pass');

$stment = $connection->prepare('INSERT INTO user VALUES (:id, :name, :idade);');
$stment->bindParam(':id', $id, PDO::PARAM_INT);
$stment->bindParam(':name', $name, PDO::PARAM_STR, 25);
$stment->bindParam(':idade', $idade, PDO::PARAM_INT);

$id = 1;
$name = 'Joao';
$idade = 18;

$stment->execute();

Is the above code not clearer than the one below?

$connection = new PDO('mysql:dbname=test;host=127.0.0.1', 'db', 'pass');

$id = 1;
$name = 'Joao';
$idade = 18;

$connection->query("INSERT INTO user VALUES ('" . sanitize($id) . "', '" . sanitize($name) "','" . sanitize($idade) . "');");
    
26.07.2016 / 05:08