2

This is the sanitization function used in a book I recently learned from - Sams Teach Yourself Ajax, JavaScript, and PHP All in One.

I've been using it on my own PHP site. Is it safe for real-world usage?

function sanitizestring($var)
{
  $var = strip_tags($var);
  $var = htmlentities($var);
  $var = stripslashes($var);
  return mysql_real_escape_string($var);
}
alex
  • 479,566
  • 201
  • 878
  • 984
MrVimes
  • 3,212
  • 10
  • 39
  • 57
  • Man this book is indeed terrible. It's author don't have a clue. If the rest of this book is the same, you will get no knowledge but ignorance . – Your Common Sense Aug 30 '10 at 07:04
  • I mentioned the wrong book in the question. But to be fair the author didn't specify that the function was an all-purpose or general purpose function. And for a beginner's book I don't expect to become a php god. I'm open to recommendations :) – MrVimes Aug 30 '10 at 15:33
  • possible duplicate of [the holy grail of cleaning input and output in php?](http://stackoverflow.com/questions/7810869/the-holy-grail-of-cleaning-input-and-output-in-php) – Kzqai Dec 02 '14 at 17:59

2 Answers2

8

I would say that is too general. It may be safe for a lot of uses, but it would often give unwanted side affects to strings. Not every string should be escaped like that.

  • mysql_real_escape_string() should be used within SQL queries only. Better still, bind params with PDO.
  • Why would you want to blanket strip tags and encode entities before inserting into a database? Maybe do it on the way out.
  • For XSS prevention, htmlspecialchars() is more of your friend. Give it the character set as an argument.

So I would use mysql_real_escape_string() for queries, and htmlspecialchars() for echoing user submitted strings. There is also a lot more to know. Do some further reading.

alex
  • 479,566
  • 201
  • 878
  • 984
1

You can also consider filter-input with those filters applied to this scope.

Aif
  • 11,015
  • 1
  • 30
  • 44