0

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

我也在此页面上使用 jQuery 验证,但无法使用它来防止 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();       
4

1 回答 1

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
}

样本来自:准备好的陈述

看看PDO 与 MySQLi的对比。

于 2012-08-23T17:53:19.860 回答