10

I read in a PHP book that it is a good practice to use htmlspecialchars and mysqli_real_escape_string in conditions when we handle user inputed data. What is the main difference between these two and where they are appropriate to be used? Please guide me.

Naeem Ul Wahhab
  • 2,347
  • 4
  • 30
  • 58
  • possible duplicate of [htmlspecialchars or mysql_real_escape_string?](http://stackoverflow.com/questions/3603146/htmlspecialchars-or-mysql-real-escape-string) – ajreal Dec 07 '11 at 16:48

4 Answers4

11

htmlspecialchars: "<" to "& lt;" (Replaces HTML-Code)

mysqli_real_escape_string: " to \" (Replaces Code, that has a meaning in a mysql-query)

Both are used to be save against some attacks like SQL-Injection and XSS

EGOrecords
  • 1,869
  • 2
  • 19
  • 33
9

These two functions are used for completely different things.

htmlspecialchars() converts special HTML characters into entities so that they can be outputted without problems. mysql_real_escape_string() escapes sensitive SQL characters so dynamic queries can be performed without the risk of SQL injection.

You could just as easily say that htmlspecialchars handles sensitive OUTPUT, while mysql_real_escape_string handles sensitive INPUT.

Shai

Shai Mishali
  • 8,156
  • 4
  • 50
  • 79
7

The two functions are totally unrelated in purpose; the only attribute they share is that they are commonly used to provide safety to web applications.

mysqli_real_escape_string is meant to provide safety against SQL injection.

htmlspecialchars is meant to provide safety against cross-site scripting (XSS).

Also see What's the best method for sanitizing user input with PHP? and Do htmlspecialchars and mysql_real_escape_string keep my PHP code safe from injection?

Community
  • 1
  • 1
Jon
  • 413,451
  • 75
  • 717
  • 787
2

htmlspecialcharacters turns 'html special characters' into code, such as quotes (both single and double), ampersands, and less than/greater than signs. This function is generally used to ensure that content users post on your website doesn't have HTML tags or XSS scripts.

mysql_real_escape_string escapes strings, meaning it adds the \ in front of slashes, quotes(both single and double), and anything else that can mess up a mysql query. This function ensures that no one is executing SQL commands on your server and getting information from the database.

Tim Withers
  • 11,941
  • 5
  • 41
  • 66