【发布时间】:2014-02-26 22:16:37
【问题描述】:
我刚刚开始学习php和mysql,所以我的知识水平对两者都比较原始。
我不太确定 stripslashes 方法,所以我想知道下面的代码是否足够安全以防止对我的数据库进行 SQL 注入或其他恶意攻击?除了 stripslashes 方法之外,添加 mysql_real_escape_string 对数据库有好处吗?
$first = Trim(stripslashes($_POST['First']));
$last = Trim(stripslashes($_POST['Last']));
$city = Trim(stripslashes($_POST['City']));
$state = Trim(stripslashes($_POST['State']));
$country = Trim(stripslashes($_POST['Country']));
$email = Trim(stripslashes($_POST['Email']));
$tempt = $_POST['tempt'];
$tempt2 = $_POST['tempt2'];
if ($tempt == 'http://' && empty($tempt2)) {
$error_message = '';
$reg_exp = "/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$/";
if(!preg_match($reg_exp, $email)) {
$error_message .= "<p>A valid email address is required.</p>";
}
if (empty($first)) {
$error_message .= "<p>Please provide your first name.</p>";
}
if (empty($last)) {
$error_message .= "<p>Please provide your last name.</p>";
}
if (!empty($error_message)) {
$return['error'] = true;
$return['msg'] = "<p>The request was successful, but the form was not filled out correctly.</p>".$error_message;
echo json_encode($return);
exit();
} else {
$return['error'] = false;
$return['msg'] = "<p style='top:9px; color:#ff6000; left:63px; text-align:left; font-size:1.50em;'>".$first .", <p style='top:0px; width:100%; left:63px; text-align:left; line-height:1.1em;'>your subscription request has been processed.</p>";
echo json_encode($return);
}
} else {
$return['error'] = true;
$return['msg'] = "<p>There was a problem while sending this form. Try it again.</p>";
echo json_encode($return);
}
【问题讨论】:
-
你真的应该使用准备好的语句来避免任何与 pdo 或 mysqli 相关的安全问题。不推荐使用 Mysql_* 函数
-
不是另外,而是,是的。 db 有他们不喜欢的字符,只有 db 驱动程序的函数知道哪些字符。这不仅仅是逃避所有
'。还有法比奥所说的。 -
如果你在 html 中打印 $first,你也应该对它进行 html 编码。为 db 转义它,而不是为 html。 Html 将其编码为 html,而不是 db。双倍永远不好。