Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cleanse a string to avoid SQL Injection and the most common types of attack? (in PHP)

Is there a way to, in as little code as possible, to filter a string for both SQL injection and the most common forms of attack?

In my scripts I'm using the following, I would like to know whether it's reasonably safe and whether someone else has a suggestion:

$cleanName    = htmlspecialchars(addslashes($dirtyName));

See how I filtered it both for html chars and for quotes and double-quotes.

NOTE: I'm using addslashes() rather than mysql_real_escape_string() because I don't want to hardcode the DB I'm using into my code.

Is this ok?

Thanks in advance

like image 700
Felipe Avatar asked Oct 16 '25 16:10

Felipe


1 Answers

Probably not... you need to escape your raw text for each purpose separately for which you are going to use it:

  • For GET requests, use urlencode.
  • For HTML output, use htmlentities.
  • For calling as a command via system, use escapeshellcmd.
  • For passing arguments to a command via system: use escapeshellargs.
  • For passing a database parameter: use mysql_real_escape_string.

There's no "universal" solution for magically escaping text. Keep raw text internally, and escape it for the appropriate purpose.

like image 185
Kerrek SB Avatar answered Oct 18 '25 08:10

Kerrek SB