What are the best practices for avoiding xss attacks in a PHP site

前端 未结 20 2350
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 02:34

I have PHP configured so that magic quotes are on and register globals are off.

I do my best to always call htmlentities() for anything I am outputing that is derive

20条回答
  •  情话喂你
    2020-11-22 03:17

    Personally, I would disable magic_quotes. In PHP5+ it is disabled by default and it is better to code as if it is not there at all as it does not escape everything and it will be removed from PHP6.

    Next, depending on what type of user data you are filtering will dictate what to do next e.g. if it is just text e.g. a name, then strip_tags(trim(stripslashes())); it or to check for ranges use regular expressions.

    If you expect a certain range of values, create an array of the valid values and only allow those values through (in_array($userData, array(...))).

    If you are checking numbers use is_numeric to enforce whole numbers or cast to a specific type, that should prevent people trying to send strings in stead.

    If you have PHP5.2+ then consider looking at filter() and making use of that extension which can filter various data types including email addresses. Documentation is not particularly good, but is improving.

    If you have to handle HTML then you should consider something like PHP Input Filter or HTML Purifier. HTML Purifier will also validate HTML for conformance. I am not sure if Input Filter is still being developed. Both will allow you to define a set of tags that can be used and what attributes are allowed.

    Whatever you decide upon, always remember, never ever trust anything coming into your PHP script from a user (including yourself!).

提交回复
热议问题