0

I would like to know if this is reliable. In my PHP file I do the following code:

if(strpos($text,"'") === false) {
    //perform query
} else { /*illegal character*/ }

I know I probably sound like an idiot, but what are the flaws in this? Can someone use different character encoding perhaps to get around it and inject a single quote?

2 Answers2

2

If you want to prevent SQL Injection - then follow the guidelines here: How can I prevent SQL injection in PHP?

Trying to implement your own custom measures is only going to end in tears.

And for the record - your code will not prevent SQL injections. For example

105; DROP TABLE Suppliers

would get through

Community
  • 1
  • 1
Laurence
  • 58,936
  • 21
  • 171
  • 212
  • So something like SELECT password FROM table WHERE username="105;DROP TABLE table"; would inject even though it's inside quotes? – Tai Kwangi Chicken Dec 12 '14 at 00:00
  • Depends on the query. But you are only currently checking for `'` anyway - not `"` - so I could use `"` and get throguh. – Laurence Dec 12 '14 at 00:02
  • @GwiddleWorker: If any query includes the variable unquoted, then checking for quotes is ineffective. Additionally, `'` can be a valid input (say if the user enters their name as `O'Leary`) so I would advise against a blanking block of specific characters. – SilverlightFox Dec 13 '14 at 11:14
  • @GwiddleWorker has this question been answered? If so - can you please accept it - or provide more info – Laurence Dec 30 '14 at 08:11
0

No, it's not. Injections can use ', ", ; and any number of other characters. For example, if you use the wrong text encoding, some Unicode characters can be used to terminate a string. As @TheShiftExchange points out, your code would let through a DROP TABLES command, and it could result in all sorts of other injections.

elixenide
  • 44,308
  • 16
  • 74
  • 100
  • So if there is a variable called $text and that variable will be placed in single quotes in the SQL query as in '$text' double quotes inside of the single quotes and semicolons inside of the single quotes can still pose threats even though I am preventing single quotes? – Tai Kwangi Chicken Dec 12 '14 at 03:54
  • Well, that's a different question than the one you asked above. I can't think of a way around what you're describing in your comment, but that doesn't mean there isn't one. You're much better off using parameterized queries than trying to do any kind of blacklisting. Tricks with character encodings, Unicode characters, and so on abound. All it takes is one improperly-filtered value to get pwned. At the very least, somebody could trigger an error in your application by passing in a value like `foo\\`. – elixenide Dec 12 '14 at 06:16