0

I'm having trouble pre-fixing the single quote ' character. I'm trying to make a simple injection prevention function ...

function injectionProtect($string) {
    $notallowed = array('\'','"','\\');
    $letters=str_split($string);
    foreach($letters as $key => $value) {
        if (array_search($value,$notallowed)>=1) {
            $letters[$key]='\\' . $value;
        }
    }
    $string=implode("",$letters);
    return $string;
}

It works for the \ and " characters, but not the ' character ... Any one know whats going wrong?

I've tried typing the ' as '\'' and "'" but neither works, it just still outputs it as '

user2864740
  • 60,010
  • 15
  • 145
  • 220
Just Lucky Really
  • 1,341
  • 1
  • 15
  • 38
  • 2
    Do not do a simple injection protection as it is futile, either do it a way that works, or don't do it at all. Are you trying to protect against SQL injection? use binder, HTML injection? use htmlescape(..) – Noam Rathaus Dec 29 '13 at 20:24
  • 3
    Don't do this. Writing your own quoting function is hard. Use the specific escaping functions available from your target environment. It'll be FAR safe, and your version is hackable/bypassable in so many ways it's not even funny. – Marc B Dec 29 '13 at 20:24
  • why you are not using stripslashes()? – Muhammad Rashid Dec 29 '13 at 20:24
  • Making a "simple injection prevention function" is inherently impossible, since the problem is not "simple". At least not as simple as you think it is. – deceze Dec 29 '13 at 20:25
  • :D ... I am aware there are already escaping functions out there, it's just a little project I'm working on, but can anyone see why it's not working for the ' character? – Just Lucky Really Dec 29 '13 at 20:29

2 Answers2

1

First of all, do not use this function to prevent SQL injection. It is not easy to create a function that can account for all possible cases of SQL injection. The correct way would be to use MySQLi / PDO with prepared statements.

Now, to answer your question:

array_search() returns the key for needle if it is found in the array, FALSE otherwise. Currently, you're checking if the return value is >=1. The single quote character is the 0th index in your array, so the code inside your if block will not get executed when the $value is '.

To know if any of the array values in $notallowed exists in $value, you could simply check if the return value is FALSE or not:

if (array_search($value,$notallowed) !== FALSE) {
    $letters[$key]='\\' . $value;
}
Amal Murali
  • 75,622
  • 18
  • 128
  • 150
  • Ohhhh, I thought it returned TRUE if it was found in the array :D Many thanks :D ... And yeah, I'm not going to be using this on any live site Lol – Just Lucky Really Dec 29 '13 at 20:32
0

Plenty of SQL injection functions exist. No need to reinvent the wheel.

elliotanderson
  • 442
  • 4
  • 14