开发者

Output HTML safely using PHP

I used stackoverflow to find solution to my problems, so I didn't need to post a question so long. I search for a way to output HTML code but as many of you answered HTMLPurifier is the best solution around.

I find it hard to believe that this is the only way, like isn't supposed that PHP thought on how to clean the input from XSS attacks but still output data?

Htmlentities, htmlspecialchars, strip_tags are not the best candidates for t开发者_JAVA百科his.

So, the question is: What is?

What I am trying to do is to output user's HTML data from MYSQL safely.


htmlentities works just fine in many cases. However, I believe the best method to prevent things like XSS is whitelisting acceptable characters. For example:

A person's name can have uppercase and lowercase letters, spaces, hyphens, and possibly apostrophes. So full names inputted into your system must match the regex /^[a-z'- ]+$/i.
Examples: Henry Smith, John O'Neil, Heather Fischer-Gardener.

An email can contain the characters uppercase and lowercase A-Z, numbers, pluses, dashes, periods, and the at symbol. So the regex for the email would be: /[a-z0-9-.+]@[a-z0-9-.]+/i.
Examples: jeff.Atwood@stackoverflow.com, spammer123@yahoo.com, leet+hacker@gmail.com, php-list@php.net

You can expand this to fit any data input. Just think about what characters could be typed. The best part about this system, is that you can allow inputs that match the regexes and record inputs that don't. You can look at the log of blocked inputs and see if you need to adjust regexes to allow valid characters or block users attempted to circumvent your security measures.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜