2
votes

This is my first time using php and I haven't a clue what I'm doing. I've taken this template and coded a html form to go with it, it all works except that there's no required fields so it can send a blank email if you click submit. I'd like it to have an error message come up when the 'name' and 'email' and 'message' inputs are empty. Can anyone help?

<?php

$EmailFrom = "[email protected]";
$EmailTo = "[email protected]";
$Subject = "T/V/C Inquiry";
$Name = Trim(stripslashes($_POST['Name'])); 
$Tel = Trim(stripslashes($_POST['Tel'])); 
$Email = Trim(stripslashes($_POST['Email'])); 
$Message = Trim(stripslashes($_POST['Message'])); 


// validation
$validationOK=true;
if (!$validationOK) {
  print "<meta http-equiv=\"refresh\" content=\"0;URL=error.php\">";
  exit;
}

// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $Name;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $Email;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $Message;
$Body .= "\n";

// send email 
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");

// redirect to success page 
if ($success){
  print "<meta http-equiv=\"refresh\" content=\"0;URL=contactthanks.php\">";
}
else{
  print "<meta http-equiv=\"refresh\" content=\"0;URL=error.php\">";
}
?>
1
Start by using if (isset($your_variable) && ($your_variable != '')) ? - Maximus2012
Next step would be to make sure that the email address is valid.php.net/manual/en/filter.filters.validate.php - Maximus2012

1 Answers

0
votes

You can use empty to check if the variable is.. empty.

$validationOK = true;
if(empty($Name) OR empty($Tel) OR empty($Email) OR empty($Message)) {
    $validationOK = false;
}
if (!$validationOK) {
    print "<meta http-equiv=\"refresh\" content=\"0;URL=error.php\">";
    exit;
}