<?php
$valid = true;
$errors = array();
$contact = array(
'name' => null,
'email' => null,
'message' => null
);
// Check if the form has been posted
if (isset($_POST['name'], $_POST['email'], $_POST['message'])) {
$contact = filter_input_array(INPUT_POST, array(
'name' => FILTER_SANITIZE_STRING,
'email' => FILTER_SANITIZE_STRING,
'message' => FILTER_SANITIZE_STRING,
), true);
if (empty($contact['name'])) {
$valid = false;
$errors['name'] = "You must enter your name.";
}
if (empty($contact['email'])) {
$valid = false;
$errors['email'] = "You must enter your email address.";
} elseif (!filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL)) {
$valid = false;
$errors['email'] = "You must enter a valid email address.";
}
if (empty($contact['message'])) {
$valid = false;
$errors['message'] = "You must enter a message.";
}
if ($valid) {
// The email address the email will be sent to
$to = "business@example.com";
// The email subject
$subject = "Contact Form Submission";
// Set the from and reply-to address for the email
$headers = "From: website@example.com\r\n"
. "Reply-To: " . $contact['email'] . "\r\n"
. "X-Mailer: PHP/" . phpversion();
// Build the body of the email
$mailbody = "The contact form has been filled out.\n\n"
. "Name: " . $contact['name'] . "\n"
. "Email: " . $contact['email'] . "\n"
. "Message:\n" . $contact['message'];
// Send the email
mail($to, $subject, $mailbody, $headers);
// Go to the thank you page
header("location: thankyou.html");
exit;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Contact Us</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<form action="contact.php" method="post" accept-charset="utf-8">
<fieldset>
<legend>Contact Us</legend>
<?php if (!$valid): ?>
<div class="error">
<?php foreach($errors as $message):?>
<div><?php echo htmlspecialchars($message); ?></div>
<?php endforeach; ?>
</div>
<?php endif; ?>
<div class="row">
<label for="name">Name: </label>
<input id="name" type="text" name="name" value="<?php echo htmlspecialchars($contact['name']);?>">
</div>
<div class="row">
<label for="email">Email Address: </label>
<input id="email" type="text" name="email" value="<?php echo htmlspecialchars($contact['email']);?>">
</div>
<div class="row">
<label for="message">Message:</label>
<textarea id="message" name="message"><?php echo htmlspecialchars($contact['message']);?></textarea>
</div>
<div class="row">
<input type="submit" value="Submit">
</div>
</fieldset>
</form>
</body>
</html>
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter