I was trying to demonstrate the need for prepared statements in PHP, but I came into a bit of a problem because PHP does some conveniently strange things with strings passed in through forms.
The statement I’m trying to “break” is a simple:
SELECT username FROM users WHERE username = '$username' AND password = '$password'
But doing something like passing in X' or TRUE;-- for the password doesn’t actually work because PHP automatically escapes the single-quote and turns the statement into:
SELECT username FROM users WHERE username = '$username' AND password = 'X\' or TRUE;--'
And the password equality remains intact because of the escaped single-quote. Is this statement considered safe? How can it be broken, if not?
It sounds like you have magic quotes turned on. I would definitely not consider that statement safe, as if you were to move it to a server running PHP 5.4, it would be completely vulnerable. Magic quotes has been a deprecated feature for a long time, and it can mess up other parts of the application, so don’t rely on it.
To demonstrate, just set
magic_quotes_gpc = Offin php.ini.