mysql_real_escape_string防止将带有错误字符的未区分化字段添加到数据库中

时间:2012-08-23 17:46:32

标签: mysql string escaping

mysql_real_escape_string阻止将带有错误字符的未清字段添加到数据库中。我不想指定每个表单上的所有字段(因为这对每个字段都很麻烦,并且不包含人们可能包含的特殊字符或拼写错误),但此时此代码阻止了任何内容如果未确定的字段中存在任何威胁字符但仍前进到下一页,则插入。

我也在这个页面上使用jQuery validate,但是无法使用它来阻止SQL注入。

   function clean($str) {
     $str = @trim($str);
     if(get_magic_quotes_gpc()) {
     $str = stripslashes($str);
     }
     return mysql_real_escape_string($str);
   }

//Sanitize the POST values
   $user_name = clean($_POST['user_name']);
   $password = clean($_POST['password']);

//Create INSERT query
   $qry = "INSERT INTO customer_info(fname, lname, gender, zip, email, phone, terms, security_question, security_answer, participating_retailers, notify_new_items, notify_promotions, priority1, priority2, priority3, priority4, priority5, privacy, user_name, password) 
 VALUES('$_POST[fname]','$_POST[lname]','$_POST[gender]','$_POST[zip]','$_POST[email]','$_POST[phone]','$_POST[terms]','$_POST[security_question]','$_POST[security_answer]','$_POST[participating_retailers]','$_POST[notify_new_items]','$_POST[notify_promotions]','$_POST[priority1]','$_POST[priority2]','$_POST[priority3]','$_POST[priority4]','$_POST[priority5]','$_POST[privacy]','$user_name','$password')";
   $result = @mysql_query($qry);  


  $qry="SELECT * FROM customer_info WHERE user_name='$user_name' AND password='$password'";  
  $result=mysql_query($qry);            
  session_regenerate_id();
        $member = mysql_fetch_assoc($result);
        $_SESSION['SESS_USER_ID'] = $member['user_id'];
        $_SESSION['SESS_FIRST_NAME'] = $member['fname'];
        $_SESSION['SESS_LAST_NAME'] = $member['lname'];
        session_write_close();
        header("location: flatter-form.html");
        exit();       

1 个答案:

答案 0 :(得分:0)

mysql_query已被弃用。 PDOmysqli都提供针对SQL注入的安全性。除了具有转义功能外,PDO还能够引用字符串。使用准备好的和参数化的查询使攻击者几乎不可能注入SQL。

$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');

$stmt->execute(array(':name' => $name));

foreach ($stmt as $row) {
    // do something with $row
}

示例来自:Prepared statements

看看PDO vs. MySQLi