Hi I’m a first time poster. I’ve been working on a site and this is the first time I attempted to implement a contact form, I used traversy media’s tutorial. I have a site for a client that is currently being hosted and dream host. I have been trying to figure out what the mistake is in my code or if its something server side I’m not doing, and have looked for ways that I may have called back the file incorrectly but I have been having trouble finding out what exactly the problem is.
Here is my code:
<?php
$msg = '';
$msgClass = '';
if(filter_has_var(INPUT_POST, 'submit')) {
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
$message = htmlspecialchars($_POST['message']);
}
//check required fields
if(!empty($email) && !empty($name) && !empty($message)) {
if(filter_var($email, FILTER_VALIDATE_EMAIL) === false){
$msg = 'Please use a valid email';
$msgClass = 'alert-danger!';
} else {
$toEmail = '[email protected]';
$subject = 'Contact Request From' .$name;
$body = '<h2>Contact Request</h2>
<h4>Name</h4><p>' .$name. '</p>
<h4>Name</h4><p>' .$email. '</p>
<h4>Name</h4><p>' .$message. '</p>
';
//main headers
$headers = "MIME-version: 1.0" ."\r\n";
$headers .="Content-Type:text/html;charset=UTF-8" . "
\r\n";
//additional headers
$headers .="From: " .$name. "<".$email.">". "\r\n";
if(mail($toEmail, $subject, $body, $headers)) {
// Email Sent
$msg = 'Your email has been sent';
$msgClass = 'alert-success'
}
$msg = 'Your email was not sent';
$msgClass = 'alert-danger';
}
}
} else {
$msg = 'Please fill in all fields';
$msgClass = 'alert-danger!';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Contact US</title>
<link rel="stylesheet" href="https://bootswatch.com/cosmo/bootstrap.min.css">
</head>
<body>
<nav class="navbar navbar-default">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="index.php">My Website</a>
</div>
</div>
</nav>
<div class="container">
<?php if($msg != ''): ?>
<div class="alert <?php echo $msgClass; ?>"><?php echo $msg; ?></div>
<?php endif; ?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control" value="<?php echo isset($_POST['name']) ? $name: '';?> ">
</div>
<div class="form-group">
<label>Email</label>
<input type="text" name="email" class="form-control" value="<?php echo isset($_POST['email']) ? $email: '';?> ">
</div>
<div class="form-group">
<label>Name</label>
<textarea name="message" class="form-control" value="<?php echo isset($_POST['message']) ? $message: '';?> "></textarea>
</div>
<br>
<button type="submit" name="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</body>
</html>
Thanks for any help that any one can give and have a good day.