Contact Form
Posted: Mon Aug 19, 2013 2:39 pm
If you've got a website and you're looking for a handy little contact form, then I've got just the thing for you. Please find the code below;
File Name: contact.php
File Name: contact.php
<?php
if (isset($_POST['submit'])) {
$errors = array();
$name=$_REQUEST['name'];
$emailaddress=$_REQUEST['emailaddress'];
$number=$_REQUEST['number'];
$response=$_REQUEST['response'];
$body=$_REQUEST['body'];
if (empty($_POST['name'])){
$errors[] = 'You must enter your name.';
}else if (!preg_match('#^[a-z ]+$#i', $_POST['name'])){
$errors[] = 'The name you entered is not valid.';
}
if(empty($_POST['emailaddress'])){
$errors[] = 'You must enter your email address.';
}else if (!filter_var($_POST['emailaddress'], FILTER_VALIDATE_EMAIL)){
$errors[] = 'That\'s not a valid Email Address.';
}
if (empty($_POST['body'])){
$errors[] = 'You must enter a message.';
}
if(empty($errors) === true){
$to = 'Your Email Address';
$subject = 'Contact Form';
$message = 'Hello,<br /><br />'.$name.' has just contacted you through the contact form, they said;<br /><i>'.$body.'</i><br /><br /><strong>Details</strong><br />Name: '.$name.'<br />Email Address: '.$emailaddress.'<br />Contact Number: '.$number.'<br />Response? '.$response.'<br /> Please use the above to contact them back if they required a response.';
$headers = 'From: Contact Form <Company Name>' . "\r\n" .
'MIME-Version: 1.0' . "\r\n" .
'Content-type:text/html;charset=iso-8859-1' . "\r\n";
mail($to, $subject, $message, $headers);
$success = "Thank you for contacting us, someone will be in contact with you soon if you said Yes to a response.";
}
}
?>
<?php if (isset($success)){ echo "<div>" . $success . "</div>";} ?>
<?php
if(empty ($errors) === false){
echo'<ul>';
foreach ($errors as $error) {
echo'<li>', $error, '</li>';
}
echo'</ul>';
}
?>
<form method="post" action="">
<label for="name"><strong>Name*:</strong></label>
<br />
<input type="text" name="name" id="name" value="<?php if (!empty($_POST['name'])) echo htmlentities($_POST['name']); ?>" /><br />
<label for="emailaddress"><strong>Email Address*:</strong></label>
<br />
<input type="text" name="emailaddress" id="emailaddress" value="<?php if (!empty($_POST['emailaddress'])) echo htmlentities($_POST['emailaddress']); ?>" /><br />
<label for="number"><strong>Contact Number:</strong></label>
<br />
<input type="text" name="number" id="number" /><br />
<label for="response"><strong>Do you need a Response?</strong></label>
<br />
<select name="response" id="response">
<option value="No">No</option>
<option value="Yes">Yes</option>
</select>
<br />
<label for="body"><strong>Message*:</strong></label><br />
<textarea name="body" id="body" cols="45" rows="5"><?php if (!empty($_POST['body'])) echo htmlentities($_POST['body']); ?></textarea><br />
<input type="submit" name="submit" id="submit" class="form_button" value="Submit" />
</form>