MultiDev
MultiDev

Reputation: 10649

Textarea protection against mysql injection- PHP

I have a textarea whose value will be inserted into a mysql database. To protect against a mysql injection, do I process the input through nl2br, mysql_real_escape_string, htmlentities, or a combination of 2 or all 3? In what order do I process the data?

Upvotes: 2

Views: 4306

Answers (3)

Andreas Wong
Andreas Wong

Reputation: 60516

nl2br basically converts all "\n" to "<br/>", so I don't see how it helps with sql injection (not mysql injection btw)

mysql_real_escape_string is usually used for this kind of thing.

htmlentities is used to prevent mishaps where users inject malicious <script> into your website if you allow user inputs. Note that it's usually an accepted practice to store string as is and only call htmlentities whenever you are outputting your string

You need to know what each of the above does and use them only when you need it, not combine them as they might break stuff even worse.

Another better and safer alternative for securing your database is to use mysqli http://sg.php.net/mysqli, it provides prepared statement to help you filter out your sql

Upvotes: 5

Explosion Pills
Explosion Pills

Reputation: 191729

The only processing you need upon insertion is mysql_real_escape_string, but it is preferred that you use prepared statements perhaps with PDO or MDB2.

Never store encoded data in a database. You should always store the raw data. That is, don't use nl2br or htmlentities for storage. You should, however, use it for display if the data is going to be inserted into the DOM (nl2br is purely visual, htmlentities will help protect against XSS). Also note that htmlspecialchars may be preferred depending upon how you want to handle the display -- this should be sufficient for basic XSS protection.

Remember this mantra:

  • Escape for storage
  • Encode for display

Upvotes: 3

user1191247
user1191247

Reputation: 12998

If you use prepared statements with PDO or mysqli then you simply bind the parameter. If using the old mysql extension then you should use mysql_real_escape_string().

Upvotes: 0

Related Questions