tags:

views:

24

answers:

4

Hey guys, I know there are a lot better ways to send email with PHP. However, for this purpose the easiest solution is perfect. Only thing: I can't find out why, my validation is not working!

I get the email address, however the validation is not working, I'm able to send a completely empty form. Any ideas?

<?php
//Email
$Name = Trim(stripslashes($_POST['author']));
$EmailFrom = Trim(stripslashes($_POST['email']));
$Subject = Trim(stripslashes($_POST['subject']));
$Comment = Trim(stripslashes($_POST['comment']));
$EmailTo = "[email protected]";

/*$Name = "Some Name";
$EmailFrom = "[email protected]";
$Subject = "Test";
$Comment = "Why is the validation not working, don't get it?";
$EmailTo = "[email protected]";*/


/*echo $Name . " length: " . strlen($Name) . "<br/>";
echo $EmailFrom . " length: " . strlen($EmailFrom) . "<br/>";
echo $Subject . " length: " . strlen($Subject) . "<br/>";
echo $Comment . " length: " . strlen($Comment) . "<br/>";
echo $EmailTo . " length: " . strlen($EmailTo) . "<br/>";*/


//***************************
//Validation
//***************************
$validationOK=true;
if ($Name == "") $validationOK=false;
if (isValidEmail($EmailFrom) == 0) $validationOK=false;
if ($Subject == "") $validationOK=false;
if ($Comment == "") $validationOK=false;
function isValidEmail( $email = null ) {
    return preg_match( "/^[\d\w\/+!=#|$?%{^&}*`'~-][\d\w\/\.+!=#|$?%{^&}*`'~-]*@[A-Z0-9][A-Z0-9.-]{1,61}[A-Z0-9]\.[A-Z]{2,6}$/ix", $email );
}

if (!$validationOK) {
  print "error";
}

//***************************
//Order
//***************************
$Body = "Contactform";
$Body .= "\n\n";
$Body .= $Comment;

// Email Headers with UTF-8 encoding
$email_header = "From: " . $EmailFrom . "\r\n";
$email_header .= "Content-Type: text/plain; charset=UTF-8\r\n";
$email_header .= "Reply-To: " . $EmailFrom . " \r\n";
// send email 
$success = mail($EmailTo, $Subject, $Body, $email_header);

//***************************
//Success or Error
//***************************
if ($success){
  print "success";
}
else{
  print "error";
}

?>
A: 

you need to return after the condition

if (!$validationOK) {
  print "error";
  // return or exit
}

dont continue to send mail

Haim Evgi
+1  A: 

You don't end your script after printing "error". You should end the script or make some other change so it won't be sent on error. For example:

if (!$validationOK) {
  print "error";
  exit;
}
Emil Vikström
A: 

This code:

if (!$validationOK) {
  print "error";
}

does not keep your program from sending a mail, it just prints error message.

Kel
A: 

You're printing the word error if $validationOK is false but you're not halting the script at that point so php continues to process the commands after it.

Try the following

if (!$validationOK) {
  print "error";
  exit();
}
acqu13sce