Prevent XSS but allow all characters?
How can I prevent XSS but allow any characters to be used? Like I can post HTML code on a forum like <html><body><h1>Test</h1></html>
, but it would not be rendered in the browser as html? How can I do this 开发者_如何学JAVAso it does not convert the characters in PHP?
Pass a string through the htmlspecialchars()
function:
// Outputs HTML as literal characters
echo htmlspecialchars('<html><body><h1>Test</h1></html>');
You can make a string safe to output with htmlentities or htmlspecialchars. htmlentities is more thorough, as it encodes all entities, while htrmlspecialchars only transforms bracket, quote and the ampersand characters.
For instance, it changes <
into <
, which is displayed by the browser as a < symbol rather than being is interpreted as the start of an HTML tag.
An interesting approach is DOM + Tidy - Source
精彩评论