gpt4 book ai didi

php + mysql 安全插入数据

转载 作者:行者123 更新时间:2023-11-30 22:54:37 24 4
gpt4 key购买 nike

我担心我的表格的安全性。这个想法是制作一个表格来参加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.";
}

}

?>

最佳答案

您正在使用 PDO,它已经实现了第一顺序注入(inject)的安全措施,当查询被参数化时,第二顺序也被阻止了(第二顺序注入(inject)意味着数据已经通过在包含在查询中之前数据库一次)

但是,如果您对输入实现验证也没有坏处。

关于php + mysql 安全插入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26967617/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com