Php + mysql安全地插入数据

时间:2014-11-17 07:31:58

标签: php mysql security

我担心表格的安全性。我们的想法是制作一张参加facebok比赛的表格。基本上只是名字,姓氏,电子邮件。我一直在搜索主题,有很多关于安全性的信息,但我无法弄清楚什么是足够的安全性? 我知道总会有人冒险滥用安全性,但我想找到一个解决方案,阻止他们中的大部分。如果有明显的错误,请告诉我。 这是我的代码,所有的帮助和指导表示赞赏。

<?php
$dsn = 'mysql:dbname=dbname;host=localhost';
$user = '';
$password = '';

try {
    $dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

$firstErr = $lastErr = $emailErr = "";
$first = $last = $email = "";

function test_input($data)
{
   $data = trim($data);
   $data = stripslashes($data);
   $data = htmlspecialchars($data);
   return $data;
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {

  if (empty($_POST["first"])) {
    $firstErr = "Name is required";
    echo "<p>Firstname: $firstErr</p>";
  } else {
    $first = test_input($_POST["first"]);
    // check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$first)) {
      $firstErr = "Only letters and white space allowed";
    echo "<p>Firstname: $firstErr</p>";
    }
  }

  if (empty($_POST["last"])) {
    $lastErr = "Name is required";
    echo "<p>Lastname: $lastErr</p>";
  } else {
    $last = test_input($_POST["last"]);
    // check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$last)) {
      $lastErr = "Only letters and white space allowed";
        echo "<p>Lastname: $lastErr</p>";
    }
  }


  if (empty($_POST["email"])) {
    $emailErr = "Email is required";
    echo "<p>Email: $emailErr</p>";
  } else {
    $email = test_input($_POST["email"]);
    // check if e-mail address is well-formed
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $emailErr = "Invalid email format";
      echo "<p>Email: $emailErr</p>";
    }
  }

    if ($firstErr == false && $lastErr == false && $emailErr == false) {
    $query = "INSERT INTO contactstable (first,last,email)  VALUES(:first,:last,:email)";
    $statement = $dbh->prepare($query);
    $statement->execute(array(
        ':first'=> $first,
        ':last'=> $last,
        ':email'=> $email
    ));
          echo "<p>Thank you for participating!</p>";
    }
    else {
        echo "Fix the missing or incorrect lines.";
    }

}

?>

1 个答案:

答案 0 :(得分:0)

您正在使用PDO,它已经实现了第一顺序注入的安全措施,当查询被参数化时,第二个订单也被阻止(2nd order injection means data has been cycled through the database once before being included in a query)

但是,如果您对输入实施验证,则没有任何害处。