Simple Contact Form with PHP

This is something that every website should have, including my personal portfolio!

The HTML

			<form id="contact_form" method="post" action="contact.php"> 
				<input id="name" type="text" name="name" tabindex="1"/> <label for="name">Name</label>
				<input id="email" type="text" name="email" tabindex="2"/> <label for="email">E-mail</label>
				<input id="website" type="text" name="website" tabindex="3" value="http://" /> <label for="website">Website</label>
				<textarea id="message" tabindex="4" rows="10" cols="60" name="message"></textarea>
				<input type="submit" value="Send E-mail" tabindex="5" />
			</form>

This is just a simple form. I included two things that increase usability quite a bit: Usage of the label tag and usage of the tabindex attribute of the various form inputs.

The label tag allows you to click the text next to an input box and have your cursor go into the textbox. You do this by setting the label’s “for” attribute equal to the “id” attribute of your input box. Find more information at w3schools.

The PHP

<?php
if( isset($_POST['action']) )
{
		echo 'Thanks for the E-mail!';
		
		$name = $_POST['name'];
		$email = $_POST['email'];
		$website = $_POST['website'];

		mail( 'send_to_this_address@to.com', "E-mail received from $name, $email, $website", $_POST['message'] );
}
?>

Now, simply put the php code followed by the HTML code into the same php file (I called mine contact.php), and upload it to your webserver!

The php is pretty simple. We grab all the form variables and put them into php’s mail function. If this function does not work, you probably need to install/configure postfix.

Discussion

The code is really simple. You can find more information in the php manual online. A big thing that I did NOT talk about, however, is how to prevent spammers from attacking your contact form. In fact, for a large site it’s a big problem (my blog gets 10+ spam messages per day).

Luckily! There is a great service available to detect and reject spam messages. It’s called Akismet. Expect a blog about this and other ways of protecting against spam in the near future.



Share this post


facebooktwittergoogle_plusredditpinterestlinkedinmail

One Response to “Simple Contact Form with PHP”

  1. Phillip Napieralski » Blog Archive » Spam-proof Contact Form with PHP - Says:

    […] Phillip Napieralski Programmer, Engineer, Researcher. « Simple Contact Form with PHP […]