2014-11-17 92 views
1

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

<?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."; 
    } 

} 

?> 

回答

0

您使用PDO,它已经实现了1次注射的安全性措施,并在查询参数化二阶也防止(2nd order injection means data has been cycled through the database once before being included in a query)

但是,如果您对输入进行验证,则没有任何危害。

+0

我希望能收到这样的答案。这几乎告诉我,为了我的目的,表单似乎足够安全。我会添加更多验证。谢谢。 – Griphon

+0

高兴地帮助你.. –

+1

[SQL注入是SQL注入,无论数据来自何处。](http://stackoverflow.com/a/22729097/53114) – Gumbo