0

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.";
}
Qirel
  • 25,449
  • 7
  • 45
  • 62
M Karizma
  • 3
  • 2
  • Where is `$name` and `$email` defined? Turn on error-reporting and see what it spits out. – Qirel Apr 25 '18 at 21:10
  • 1
    Well, if you haven't entered any text I assume you haven't submitted the form yet. If that's the case, then `isset($_POST['name'])` will be `false` (no form submission means no "name" field was posted) and you'll end up in your `else` condition. – rickdenhaan Apr 25 '18 at 21:11
  • $name and $email are like this $name = $email = " "; – M Karizma Apr 25 '18 at 21:11
  • So you're not setting it to the POST-values then? There's your issue. – Qirel Apr 25 '18 at 21:11
  • I had it to POST value before but then I was getting error undefined index for $name and $email – M Karizma Apr 25 '18 at 21:12
  • Which indicates that you're not sending the proper values over POST. We're really not seeing enough to give you any further advice here. You need to show some more code and relevant errors. – Qirel Apr 25 '18 at 21:14
  • 1
    Sidenote: `and` and `&&` are not necessarily the same thing. See [this question](https://stackoverflow.com/q/2803321/1941241) and its answers for things to look out for. – rickdenhaan Apr 25 '18 at 21:20

1 Answers1

2

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.";
    }
}
Syscall
  • 19,327
  • 10
  • 37
  • 52
  • You should move the definition of `$email` and `$name` before the second condition, or it won't work. – Qirel Apr 25 '18 at 21:18
  • Thank you @Syscall , I thought initially to do like that but I didn't and thank you guys for your help and suggestions. – M Karizma Apr 25 '18 at 21:25