-2

I want to protect my web app from SQL_Injection. Here's the function I wrote but I want your opinion about it and if you have any tips to improve it! Thank you in advance!

function charfilter($String)
{ /*Sanitize input*/
    $count=0;
    $forbidden= array("'",";","--","=","\"","#","<",">");
    $String=str_replace($forbidden," ", $String,$count);
    // String lenght limited to MAX_BUFF
    return substr($String,0,MAX_BUFF);
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
Sara Briccoli
  • 141
  • 3
  • 11
  • 4
    [`prepare()`](https://www.php.net/manual/en/pdo.prepare.php) is the function you need to prevent from an SQL injection - why are you trying to re-invent the wheel worse? Your logic fails to stop a `1 OR 1` injection... – Jaquarh Feb 24 '21 at 13:48
  • 1
    I think you're thinking of HTML injection, not SQL injection, as very few of the characters you're replacing have any effect on an SQL string. You don't have to worry about html characters going into the database, just convert them on the way back out with functions such as [htmlspecialchars](https://www.php.net/manual/en/function.htmlspecialchars.php) – aynber Feb 24 '21 at 13:50
  • I didn't know about it so thank you so much! I'm going to read prepare() on documentation – Sara Briccoli Feb 24 '21 at 13:51
  • In such case you should start from the basics, as lot of stuff is already done and the best way is to follow it as SQL injection prevention is very well done nowadays. And please don't get this comment as an irony. – biesior Feb 24 '21 at 13:52
  • 1
    Does this answer your question? [How can I prevent SQL injection in PHP?](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – El_Vanja Feb 24 '21 at 13:52

1 Answers1

0

You are relying on blacklisting which is not effective in this case: there will always be an edge case where your custom filter will be bypassed.

Use prepared statements!

If this is not possible, then use the proper escaping for your DBMS (they are all different). For example, mysqli_escape_string. Just know that there exist still some edge cases that can bypass that too...

Palantir
  • 23,820
  • 10
  • 76
  • 86
  • How it can be "not possible" to use prepared statements? How "proper escaping" is related to SQL injections? – Your Common Sense Feb 24 '21 at 14:07
  • Was that supposed to be sarcastic? Anyway. 1. OP did not mention MySql. Are you sure that every DBMS out there supports prepared statements? 2. "Using a prepared statement is not always the most efficient way of executing a statement." (from the PHP manual about prepared statements) 3. Also, try get yourself a MariaDB installation and try running a prepared statement on a view. Hint: https://jira.mariadb.org/browse/MDEV-17124 – Palantir Feb 25 '21 at 08:15