dongxiezhi0590 2011-05-11 12:43
浏览 18
已采纳

PHP:有关用户输入如何“免疫”的建议

I usually escape user input by doing the following:

htmlspecialchars($str,ENT_QUOTES,"UTF-8");

as well as mysql_real_escape_string($str) whenever a mysql connection is available.

How can this be improved? I have not had any problems with this so far, but I am unsure about it.

Thank you.

  • 写回答

3条回答 默认 最新

  • dtsjq28482 2011-05-11 14:25
    关注

    Data should be escaped (sanitized) for storage and encoded for display. Data should never be encoded for storage. You want to store only the raw data. Note that escaping does not alter raw data at all as escape characters are not stored; they are only used to properly signal the difference between raw data and command syntax.

    In short, you want to do the following:

    $data = $_POST['raw data'];
    //Shorthand used; you all know what a query looks like.
    mysql_query("INSERT " . mysql_real_escape_string($data));
    
    $show = mysql_query("SELECT ...");
    echo htmlentities($show);
    // Note that htmlentities() is usually overzealous.
    // htmlspecialchars() is enough the majority of the time.
    // You also don't have to use ENT_QUOTES unless you are using single
    // quotes to delimit input (or someone please correct me on this).
    

    You may also need to strip slashes from user input if magic quotes is enabled. stripslashes() is enough.

    As for why you should not encode for storage, take the following example:

    Say that you have a DB field that is char(5). The html input is also maxlength="5". If a user enters "&&&&&", which may be perfectly valid, this is stored as "&&." When it's retrieved and displayed back to the user, if you do not encode, they will see "&&," which is incorrect. If you do encode, they see "&&," which is also incorrect. You are not storing the data that the user intended to store. You need to store the raw data.

    This also becomes an issue in a case where a user wants to store special characters. How do you handle the storage of these? You don't. Store it raw.

    To defend against sql injection, at the very least escape input with mysql_real_escape_string, but it is recommended to use prepared statements with a DB wrapper like PDO. Figure out which one works best, or write your own (and test it thoroughly).

    To defend against XSS (cross-site-scripting), encode user input before it is displayed back to them.

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

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测