Hey everyone,
Hope everyone is doing well! So I might seem a little dumb to post this but I've googled and searched every possible thing I can think of to get my contact form to work and send an email. The validation, which in this case is defaulted to jquery works fine. it's when I submit the script to send an email that has the issue. Can anyone look at my code and tell me what I'm doing wrong? Thanks in advance!
//top of page
<?php
$hasError = false;
$sent = false;
if(isset($_POST['submit'])){
$name = trim(htmlspecialchars($_POST['name'], ENT_QUOTES));
$email = trim($_POST['email']);
$message = trim(htmlspecialchars($_POST['message'], ENT_QUOTES));
$fieldsArray = array(
'name' => $name,
'email' => $email,
'message' => $message
);
$errorArray = array();
foreach($fieldsArray as $key => $val){
switch ($key){
case 'name':
case 'message':
if(empty($val)){
$hasError = true;
$errorArray[$key] = ucfirst($key) . " field was left empty.";
}
break;
case 'email':
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$hasError = true;
$errorArray[$key] = "Invalid Email Address Entered";
}else{
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
}
break;
}
}
if($hasError !== true){
$to = "myemailaddress@myemail.com";
$subject = "New subject!";
$msgcontents = "Name: $name<br>Email: $email<br>Message: $message";
$headers = "MIME-Version: 1.0 \r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1 \r\n";
$headers .= "From: $name <$email> \r\n";
$mailsent = mail($to, $subject, $msgcontents, $headers);
if($mailsent){
$sent = true;
unset($name);
unset($email);
unset($message);
}
}
}
?>
//above form
<?php
if($sent === true){
echo "<h2 class='success'>Thanks! Your message has been sent successfully!</h2>";
}elseif($hasError === true){
echo '<ul class="errorlist">';
foreach($errorArray as $key => $val){
echo "<li>" . ucfirst($key) . " field error - $val</li>";
}
echo '</ul>';
}
?>
Thanks again! Any help is very much appreciated!