繁体   English   中英

PHP Cookie安全性问题

[英]PHP Cookie Security Question

我有以下代码表示“日常词汇”,由于我是php编码的新手,所以我想确保我从数据库中选择的方式没有任何安全性问题Cookie值。 谢谢。

if ($word_of_the_day) {
   $wotd = $wpdb->get_results("SELECT term,definition FROM glossary WHERE term = '{$word_of_the_day}'");
   foreach ($wotd as $term) { }
}
elseif ($_COOKIE['WOTD']) {
   $word_of_the_day = htmlspecialchars(addslashes($_COOKIE['WOTD']));
   $wotd = $wpdb->get_results("SELECT term,definition FROM glossary WHERE term = '{$word_of_the_day}'");
   foreach ($wotd as $term) { }
}
else {
   $wotd = $wpdb->get_results("SELECT term,definition FROM glossary ORDER BY RAND() LIMIT 1");
   foreach ($wotd as $term) {
      setcookie("WOTD", $term->term, time()+86400);
   }
}

好吧,如果$ word_for_the_day来自用户输入,则是您的第一个问题。 使用它之前,请执行以下操作:

$word_for_the_day = mysql_real_escape_string($word_for_the_day);

您的cookie实际上看起来不错。 在您使用它们的上下文中,htmlspecialchars()和addslashes()调用似乎不容易受到SQL注入或XSS攻击。

您应该检出mysql_real_escape_string :“在字符串中转义特殊字符以用于SQL语句”。 您无需手动处理htmlspecialchars addslashes 您熟悉SQL注入安全性风险吗? 如果要包含在SELECT语句中的变量$word_of_the_day来自用户,则可能存在SQL注入问题。

Addslashes非常弱。 首先,运行通过mysql_escape_string从数据库查询的所有内容以防止sql注入。 那只是基础。

if($word_of_the_day){

$word_of_the_day = mysql_escape_string($word_of_the_day); 
 $wotd = $wpdb->get_results ("SELECT term,definition FROM glossary WHERE term = '{$word_of_the_day}'");

而且,无论您编写的代码多么安全,cookie总体上都不是很安全。 对于更安全的解决方案,建议您使用PHP会话($ _SESSION)。 您可以将变量存储在此超全局变量中,并且它将在两次页面加载之间保持不变。

http://www.php.net/manual/zh/session.examples.basic.php

之后,如果您确实要这样做,则可能要防止会话劫持或中毒

您可以考虑的另一种选择是将单词的ID而不是单词本身存储在Cookie中。 这样,它只能是整数。 当然,使用单词也可以,只要首先使用mysql_real_escape_string ,我只想提供另一个选择。

最安全的方法之一是使用PDO MySQL函数,该函数实现参数:

$db = new PDO('mysql:host=hostname;dbname=defaultDbName', 'username', 'password');
$stmt = $db->prepare('SELECT term,definition FROM glossary WHERE term = :wotd');
if ($stmt) {
    if ($stmt->execute(array(':wotd' => $word_of_the_day))) { //This is safe for any input method
        $info = $stmt->fetchAll();
        foreach($info as $row) {
            //Whatever
        }
    }
}

PDO驱动程序根据表中的数据类型进行正确的转义/引用。

$ word_of_the_day来自哪里? 如果来自用户输入,则可以进行SQL注入。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM