-2

I'm trying to do an email validation.

I've got an input text field which I write to a file when the user enters data into the input field.

I would like to have a simple code which would check if the email is valid, and if the email isn't valid go back to the original page and don't add it to the .txt file

Currently I have:

// only do file operations when appropriate
if(isset($_POST['email']) && (filter_var($a, FILTER_VALIDATE_EMAIL)) {
    $a = $_POST['email'];
    $myFile = "email.txt";
    $fh = fopen($myFile, 'a') or die("can't open file");
    fwrite($fh, $a);
    fclose($fh);
}
else
{
    echo "Email is not Valid" . "<script>history.back()</script>";
}

As you can see I haven't figured out how to not add it to the text file yet, however I would like to just get the email filter working first. Could anyone help me with this problem?

Edit: I also keep getting the error:

Parse Error: syntax error, unexpected '{' in "C:.......\authorized.php on line 59

Which is the opening bracket to the if statement?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Andrew Glass
  • 423
  • 2
  • 7
  • 18
  • 1
    I think I'm missing the point. What are you actually having trouble with? Your code appears to only write to file when the email is valid according to the FILTER_VALIDATE_EMAIL flag. What are you actually having issues with? – Kye Nov 05 '13 at 11:22
  • I think you haven't enabled full error reporting so you've not been notified that `$a` is used before it's defined. That's something you need to fix before you go further; it's impossible to code properly without the aid of error messages. Here's a [brief explanation](http://stackoverflow.com/a/5680885/13508). – Álvaro González Nov 05 '13 at 11:26
  • About your edit: Stack Overflow is definitively not an online syntax checker, but we cannot help you find an error on line #59 with an 11 line snippet. – Álvaro González Nov 05 '13 at 11:31
  • the problem was the '(' before the filter_var, so now it only writes to a file when the email is a valid email. – Andrew Glass Nov 05 '13 at 11:34

2 Answers2

1

I think the problem might be you are using $a which is not defined in your if condition checking

I thnk you should have

if(isset($_POST['email']) && (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))) 

instead of

if(isset($_POST['email']) && (filter_var($a, FILTER_VALIDATE_EMAIL))
Pavan Kumar
  • 406
  • 1
  • 4
  • 16
0

There is an error in your code. You are checking $a variable in the "if" but this variable is defined after, inside the if. You can use filter_input instead filter_var:

$a = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
  • You have missed some parenthesis: (isset($_POST['email']) && ($a = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL)))) { – Oscar Otero Nov 05 '13 at 11:29