In below code I am getting error message Sorry your name is not in correct format
even before I enter any text. Can anyone tell me what mistake am I making ?
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.";
}
You have to separate your condition in two if
statements. The first to check if something was posted. The second to check if the input are valid. The else
statement should go under the second if
(if the input are not valid).
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.";
}
}