0

I got a $_GET and users are able to send the $_GET string to the MySQL, so quick question:

Is this query:

mysql_query("SELECT XX FROM ZZ WHERE YY %LIKE% " . htmlspecialchars($_get['string']) . ";");

enough to be safe? or I should add something more than htmlspecialchars() to be safe?

Thank you in advance for all replies.

user229044
  • 232,980
  • 40
  • 330
  • 338
Lucas
  • 3,517
  • 13
  • 46
  • 75

3 Answers3

3

Unsafe.

Trivial example data that even shows htmlspecialchars doing "it's thing" -- it's just the wrong "thing".

1;DROP TABLE all_your_precious_data--&

Happy coding.


Solution: Use placeholders as per PDO or mysqli (or use mysql_real_escape_string if you wish to keep promoting outdated practices...)

See Best way to stop SQL injection in PHP and Prevent injection SQL with PHP and Can SQL injection be prevented with just addslashes?

Community
  • 1
  • 1
  • Yes, there are solutions. Added useful links to other SO questions on the topic. The first link is particular good and shows a trivial example with PDO. –  Sep 08 '11 at 23:36
  • 1
    @Lucas Also look at the *negative answers* and comments in those links as well -- there is as much to be learned from those (not so good approaches) as the good answers. –  Sep 08 '11 at 23:42
2

htmlspecialchars has nothing to do with MySQL. It's for escaping HTML special characters, characters that have special meaning when evaultated as HTML. You should use it before you write untrusted data to the browser, not to the database.

You need to remove htmlspecialchars entirely, and use mysql_real_escape_string, or better yet, PDO.

user229044
  • 232,980
  • 40
  • 330
  • 338
  • So using mysql_real_escape_string is the only way, to be fully safe in this case? Also I don't need anything more?:) – Lucas Sep 08 '11 at 23:35
  • @Lucas No. It's not the "only way". Read to the end of the sentence. –  Sep 08 '11 at 23:36
  • 1
    You can use `mysql_real_escape_string` as a drop-in replacement, but you *should* be using PDO. – user229044 Sep 08 '11 at 23:36
  • Then if I'll switch to the PDO, then I can say I'm fully safe?:) Also, how would it'll have to look like, if I'd be using PDO? – Lucas Sep 08 '11 at 23:38
  • 1
    @Lucas Look. There is nothing you can do to say you're "fully safe", so stop asking after that. The fact that you're asking this stuff is a pretty good indication that you have no idea what you're doing. It's impossible for *experts* to make a non-trivial web app "fully safe", and they actually *know* what they're doing. Read the links in pst's answer, and then read some more, and then when you're done reading, go read some more. We can't tell you how to magically make your entire app secure with one function. Web security is an incredibly complex topic. – user229044 Sep 08 '11 at 23:42
0

It's probably unsafe, and you'd better use mysql_real_escape_string.

yhager
  • 1,632
  • 15
  • 16