我有一个包含 html 电子邮件表单的 php 文件,并且我有位于 html 代码之上的服务器端表单验证。我只有基础知识,我想知道是否有人能够判断下面的验证代码是否正确(我还在代码中插入了一些问题)。谢谢!
<?php
// define variables and set to empty values
$nameErr = $emailErr = $messageErr = $keywordErr = "";
$name = $email = $message = $keyword = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains specific names - is this ok?
if (!preg_match("/^[Apollo, Mars, Venus, Sofia]*$/", $name)) {
$nameErr = "Only preset names allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed - is this ok and where does the "FILTER_VALIDATE_EMAIL" reside?
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["message"])) {
$messageErr = "Message is blank";
} else {
$message = test_input($_POST["message"]);
}
if (empty($_POST["keyword"])) {
$nameErr = "Answer is required";
} else {
$name = test_input($_POST["keyword"]);
// check if answer matching - is expression correct?
if (!preg_match("/^[Actual answer words]*$/", $keyword)) {
$keywordErr = "Incorrect answer. Please try again.";
}
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
我根据“W3学校”的php代码教程检查了代码,但我不清楚它是否足够安全,以及我尝试自定义的表达式以及我有问号的地方。我还计划在文件中进行 html 客户端验证,但这是另一个问题。