I have created a simple contact form using a bit of PHP code and allowed it to give errors in certain circumstances, such as if a field is empty, or the contents of the field do not match certain criteria. I have applied the standard criteria to the email input box (eg. must contain '@' symbol. But even when all the correct criteria are matched, my PHP still throws and error.
Here is the code:
<?php
if(isset($_POST['email'])){
// Here is the email to information
$email_to ="info@example.co.uk";
$email_subject ="example.co.uk contact form";
$email_from ="Website Contact Form";
// Error Code
function died($error) {
echo 'Sorry, there is a problem with the form you submitted. ';
echo 'These errors appear below.<br/><br/>';
echo $error. '<br/><br/>';
echo 'Please go back and fix these errors.';
die();
}
// Validation
if(!isset($_POST['name']) ||
!isset($_POST['email']) ||
!isset($_POST['comments'])){
died('All fields must be filled out.');
}
$name = $_POST['name'];
$email = $_POST['email'];
$comments = $_POST['comments'];
$error_message = "";
$email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]
{2,4}$/';
if(!preg_match($email_exp, $email)){
$error_message .= 'The Email Address you entered does not appear to be valid.';
}
$string_exp = "/^[A-Za-z.'-]+$/";
if (!preg_match($string_exp, $name)){
$error_message .= 'The Name you entered does not appear to be valid.';
}
if (strlen($comments) < 2 ){
$error_message .= 'The Comments you entered do not appear to be valid.<br/>';
}
if (strlen($error_message) > 0 ){
died($error_message);
}
$email_message = "Form Details Below. \n\n";
function clean_string($string){
$bad = array("content-type", "bcc:", "to:", "cc:", "href");
return str_replace($bad, "", $string);
}
$email_message .= "Name:" . clean_string($name) . "\n";
$email_message .= "Email:" . clean_string($email) . "\n";
$email_message .= "Comments:" . clean_string($comments) . "\n";
// Create Email Headers
$headers = 'From: ' .$email_from . "\r\n". 'Reply-To:' . $email. "\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);
?>
<html>
<!-- success message goes here-->
Thank You for contacting us, we will be in touch shortly. <br/>
Please Click <a href="contact.html">here<a/> to go back to the contact page.
</html>
<?php } ?>
Does anyone understand why it is still giving me error messages?