-1

I started trying to write a php script to validate the email address that the user enters in my form. Can anybody please help me to finish it? Thanks in advance. Your help will be greatly appreciated :) NOTE: Please do not tell me to use javascript or jQuery. I need to do this with php :/

<?php
$mail = $_POST['mail'];
$formcontent = "Email: $mail";
$recipient = "email@example.com";
$subject = "Mail that uploaded picture";
$mailheader = "From: my website";

if ($mail == ""){
echo "Please enter a valid email address. We want to contact you using your email address. Do not worry, nobody will be able to see it.";
}

else{
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo 'Your email address has been successfully added to your photo !<br>We will contact you later to tell you how to win the $50 000 :)<br><br>';}

?>
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
OS_
  • 3
  • 2

2 Answers2

2

Like this:

$email = 'email@example.com';
if (filter_var($email, FILTER_VALIDATE_EMAIL)){
    echo 'Email OK';
}

In your source code:

$mail = $_POST['mail'];
$formcontent = "Email: $mail";
$recipient = "email@example.com";
$subject = "Mail that uploaded picture";
$mailheader = "From: my website";

if (!filter_var($mail, FILTER_VALIDATE_EMAIL)){
    echo "Please enter a valid email address. We want to contact you using your email address. Do not worry, nobody will be able to see it.";
} else {
    mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
    echo 'Your email address has been successfully added to your photo !<br>We will contact you later to tell you how to win the $50 000 :)<br><br>';
}    
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
1

Ideally you should also be checking to see if $_POST['mail'] is defined because you will get an error / notice depending on your error_reporting level and display_errors.

Updated code:

if (!isset($_POST['mail']) || !filter_var($_POST['mail'], FILTER_VALIDATE_EMAIL)) {
    echo "Please enter a valid email address. We want to contact you using your email address. Do not worry, nobody will be able to see it.";
} else {
    $mail = $_POST['mail'];
    $formcontent = "Email: $mail";
    $recipient = "email@example.com";
    $subject = "Mail that uploaded picture";
    $mailheader = "From: my website";

    mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
    echo 'Your email address has been successfully added to your photo !<br>We will contact you later to tell you how to win the $50 000 :)<br><br>';
}
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Thomas Lomas
  • 1,553
  • 10
  • 22
  • Your suggestion is `if ($mail == "" || !filter_var($mail, FILTER_VALIDATE_EMAIL)){}`, but the `$mail == ""` is not needed in the condition. –  Apr 22 '14 at 22:10
  • Good call, i've updated the code to also check if $_POST['mail'] is actually set. – Thomas Lomas Apr 22 '14 at 22:16