在下面的代码中,即使在输入任何文本之前,我收到错误消息Sorry your name is not in correct format
。谁能告诉我我犯了什么错误?
if ((isset($_POST['name'])) and(isset($_POST['email'])) and (filter_var($email, FILTER_VALIDATE_EMAIL)) and (preg_match('/^[A-Za-z0-9\s]+$/', $name))) {
//if yes, it is writing it into file
$myfile = fopen("names.txt", "w") or die("Unable to open file!");
$txt = $name . "\r\n" . $email;
fwrite($myfile, $txt);
fclose($myfile);
}
else {
echo "Sorry, your name is not in correct format.";
}
答案 0 :(得分:2)
您必须在两个if
语句中分隔您的条件。第一个检查是否发布了某些内容。第二个检查输入是否有效。 else
语句应该在第二个if
之下(如果输入无效)。
if (isset($_POST['name']) && isset($_POST['email']))
{
$name = $_POST['name']; // get data from $_POST
$email = $_POST['email']; // get data from $_POST
if (filter_var($email, FILTER_VALIDATE_EMAIL) && preg_match('/^[A-Za-z0-9\s]+$/', $name))
{
//if yes, it is writing it into file
$myfile = fopen("names.txt", "w") or die("Unable to open file!");
$txt = $name . "\r\n" . $email;
fwrite($myfile, $txt);
fclose($myfile);
}
else {
echo "Sorry, your name or email are not in correct format.";
}
}