0

Is it enough to replace all single quotes in a T-SQL statement with double quotes to prevent injections?

I have this PHP function to escape user input which is then executed directly.

<?php

    function clean($input) {
        return str_replace('\'', '\'\'', $input);
    }

    echo 'INSERT INTO Temp ([test]) VALUES (\'' .clean($_GET['test']). '\')';

Example: $_GET['test'] is 'test, it would be escaped to '''test'.

I know, I should use prepared statements, but I want to know if this is vulnerable.

Dale K
  • 25,246
  • 15
  • 42
  • 71
chiaos
  • 1
  • 2
  • 9
    Using a prepared (parametrised) statement is always the way to go. – Thom A Oct 21 '19 at 08:51
  • In short, Yes, you can use preg_replace to modify your output. – pc_ Oct 21 '19 at 10:10
  • No, it's not. sanitizing inputs is the wrong way to go. I remember about 13-14 years ago getting our databases hacked via injection even though we did have a string replace sanitation function and everything that went to the database was through it. Use parameters. That's what they are there for. – Zohar Peled Oct 22 '19 at 04:42
  • Take a look at [this question and the accepted answer](https://stackoverflow.com/questions/15537368/how-can-sanitation-that-escapes-single-quotes-be-defeated-by-sql-injection-in-sq). It's not exactly like your example, but it may help you to understand why using parameterized queries is the best approach. – Zhorov Oct 23 '19 at 14:18

0 Answers0