Here is another post containing a snippet of code that you can use in your own project or just so that you can store it in your "Useless Snippets Folder" on your Desktop. You can view all of the older code snippet articles by browsing the code snippet category list.

This time I will be showing you how to create yourself a very simple contact form for use on your blog or website. It will consist of just two files – one being the PHP script to send the mail and the other being the HTML that can be used to send the mail – and I will explain how to use them and what they do.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php
if(isset($_POST['submit'])) {
	$to = "you@yourdomain.com"; // E-mail address to send to.
	$prefix = "[Bull3t's Blog] Simple Contact Form: "; // Subject prefix.
 
	$name = $_POST['name'];
	$email = $_POST['email'];
	$subject = $prefix . $_POST['subject'];
	$message = $_POST['message'];
 
	$body = "From: " . $name . "\nE-Mail: " . $email . "\nMessage:\n" . $message;
 
	if (mail($to, $subject, $body) == true) {
		echo "Thankyou, " . $name . ". Your form was successfully submitted.";
	} else {
		echo "There was an error whilst sending your message, please try again later.";
	}
}
?>

This is the PHP script that will be used to send the mail to you, all you need to do is change the $to variable to your e-mail address and the $prefix variable to whatever you want the prefix of the subject to be. Then save it as send.php and upload it to your website.

The next step is to add the form itself, to do this you need to save a simple HTML file containing a form, which, when submitted, sends the information from the text boxes to the send.php file and in turn, sending the mail.

View Code HTML4STRICT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<html><form method="post" action="send.php">
	Name: <br />
	<input type="text" name="name" size="19"><br /><br />
 
	E-Mail Address: <br />
	<input type="text" name="email" size="19"><br /><br />
 
	Subject: <br />
	<input type="text" name="subject" size="19"><br /><br />
 
	Message: <br />
	<textarea rows="9" name="message" cols="30"></textarea><br />
 
	<input type="submit" value="Submit" name="submit">	
</form></html>

As you can see, all that it consists of is a series of text boxes for your user to type in their details, quite simple really, and there is no need for JavaScript. This file should be saved as index.html and uploaded to your website in the same directory as send.php. Then navigate to the index.html on your website and test the form, if all went well you should get a page telling you it was successfully sent, if you receive an error message, however you may want to check with your host to see whether they allow the PHP mail function.