我有一个html表单(方法POST,链接到以下PHP脚本等),但无法看到我的脚本无法正常工作的原因。
应该从表单(mname,memail)中获取名称和电子邮件,验证它们,然后将值保存到“mailinglist.csv”中。我不能让它工作。
这是我的剧本:
<?php
//variables set to empty
$mnameErr = $memailErr = "";
$mname = $memail = "";
//validate name
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(empty($_POST["mname"])) {
$mnameErr = "Name is required";
} else {
$mname = test_input($_POST["mname"]);
//checks if name only contains letters and whitespaces
if (!preg_match("/^[a-zA-Z ]*$/",$mname)) {
$mnameErr = "Only letters and white space allowed";
}
}
//validate email
if (empty($_POST["memail"])) {
$memailErr = "Email is required";
} else {
$memail = test_input($_POST["memail"]);
//checks if email address is well-formed
if (!filter_var($memail, FILTER_VALIDATE_EMAIL)) {
$memailErr = "Invalid email format";
}
}
//validate data function
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
//saves details to mailinglist.csv
if($memailErr != "")
{
echo("There was an error.");
} else {
$fs = fopen("mailinglist.csv","a");
$txt = $mname.", ".$memail."\n";
fwrite($txt);
fclose($fs);
header("Location: thankyou.html");
}
exit;
}
}
?>