Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use which string escaping method? [closed]

Tags:

security

php

Okay, so there's all these different string-escaping functions such as htmlentities(), mysql_real_escape_string(), addslashes()

But which should I use in what situation?
Resources and opinions please :)

like image 590
Joshwaa Avatar asked Mar 02 '26 04:03

Joshwaa


2 Answers

  • addslashes() / stripslashes() goes back to a rather bad idea called 'Magic Quotes' which has since been deprecated. It automatically escaped special characters, and you could then use addslashes() and stripslashes() to add or remove them. One of the problems was that you were never quite sure whether the data currently had slashes or not, and thus you ended up putting unescaped data into SQL, or had extra slashes on your web page.
  • htmlentities() is used often to display HTML on the page. If you try to write <b>Something</b> to a HTML page, you will just see Something (i.e. the original text in bold) - you won't see the bold tags around it. Using htmlentities('<b>Something</b>') converts the code to <b>Something<b> so in the browser you see the triangle brackets.
  • mysql_real_escape_string() is useful for defending against MySQL injection attacks - it escapes unsafe characters in strings. It does not escape anything in other data types, and so those need to be dealt with separately. It also does not encode % and _, which are used as wildcards in some queries.

In summary:

  • If you're encoding to write to a HTML page, use htmlentities()
  • If you're encoding a string to write to a database, use mymysql_real_escape_string()
  • Never use addslashes()
like image 68
Dan Blows Avatar answered Mar 04 '26 16:03

Dan Blows


which should I use in what situation?

  • htmlentities(). never use it, but htmlspecialchars(). For printing untrusted user input into browser.
  • mysql_real_escape_string is mysql database specific function. here is a comprehensive guide I wrote exactly on topic where to use it and where not and what else you need to know on mysql database security
  • addslashes(). it depends. most of time you just don't need it at all
like image 35
Your Common Sense Avatar answered Mar 04 '26 16:03

Your Common Sense