0

How can I validate a HTML code submitted by the user? Looking for <script> tags is easy, but you can also embed JS in for example <div onclick="yyy"></div>. Are there any ready to use libraries/functions? (like $safeHTML = validateCode($rawHTML))

2 Answers2

0

You can use HTML Purifier.

Aurelio De Rosa
  • 21,856
  • 8
  • 48
  • 71
-1

I use the following function:

function sanitizeString($var){
    $var = strip_tags($var);
    $var = htmlentities($var);
    $var = stripslashes($var);
    return mysql_real_escape_string($var);

It changes over characters like < to

&lt;

prevent escape characters for SQL, stips unwanted slashes, etc.

Dennis
  • 138
  • 1
  • 4
  • 1
    -1 This doesn't validate anything and looks like a bad collection of different stuff. `strip_tags()` might break your html, makes it unusable later and doesn't like malformed tags (something like `<script>`, or similar); `stripslashes()` might be useful only in the ever more rare event of magic_quotes enabled; `mysql_real_escape_string()` is a MySQL escaping function, and doesn't work without an open connection (returning FALSE from all your beautiful sanitizer) or with INTs; HTML and DB are irrelated destination,need to be treated as such. Escape only for the target, not _a priori_ – Damien Pirsy Oct 29 '11 at 14:37