Is htmlentities best solution to prevent XSS in PHP? Also I would like to allow simple tags like b, i, a and img. What would be the best solution to implement this? I did consider bbcode but found out if not implemented properly I too will have XSS problem. What should I do? Any good third-party library is welcome.
EDIT:
I just tried HTML Purifier and it failed on this case. Just see this example
…………………………………………
For that, I would go for the HTML Purifier, and yes you can specify your whitelist tags there too.
HTML Purifier is a standards-compliant HTML filter library written in PHP. HTML Purifier will not only remove all malicious code (better known as XSS) with a thoroughly audited,
secure yet permissive whitelist, it will also make sure your documents are standards compliant, something only achievable with a comprehensive knowledge of W3C’s specifications.
I know there are certain functions in PHP language for that but I would prefer a dedicated solution instead.
…………………………………………
have a look at custom markup languages like markdown (used by stackoverflow), reStructuredText, textile or similar lightweight markup languages
…………………………………………
Try using this code (it allows for , and $html = ‘Inline ‘; function escapeEveryOther(&$v, $k) { $parts = preg_split(‘`(?(?:b|i|del)>)`is’, $html, -1, PREG_SPLIT_DELIM_CAPTURE); $html = implode(”, $parts); and then pass $html through HTMLPurifier to fix non matching tag openings and closings.):
context
if($k % 2 == 0) {
$v = htmlspecialchars($v);
}
}
array_walk($parts, ‘escapeEveryOther’);