PHP contact form

16.Dec.2010

So, almost every website needs contact form – is it a real contact form or just a feedback from your users. We need to make a contact form as easy to deal with as possible. There is a simple way of dealing with all elements on your contact form by doing a simple trick. We are going to use a name convention to easily get all elements entered by user, to wrap them, and finally – to get them sent to the website owner.

First we shall start with a little bit of HTML as it is necessary for our contact form to live. Here – we are going to use our name convention to easily deal with details.

HTML contact form:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<form action="contact.php" method="post">
<dl class="php_contact_form">
	<dt>
		<label for="php_contact_form[email]">E-mail:</label>
	</dt>
	<dd>
		<input type="text" name="php_contact_form[email]" />
	</dd>
	<dt>
		<label for="php_contact_form[subject]">Subject:</label>
	</dt>
	<dd>
		<input type="text" name="php_contact_form[subject]" />
	</dd>
	<dt>
		<label for="php_contact_form[message]">Message:</label>
	</dt>
	<dd>
		<textarea type="text" name="php_contact_form[message]" ></textarea>
	</dd>
	<dt>
 
	</dt>
	<dd>
		<input type="submit" value="Submit" />
	</dd>
</dl>
</form>

Now – you might have noticed that all names are in “array” naming convention. They all belong to a single parameter that is going to be posted: php_contact_form.

As we are posting data from our PHP contact form to a contact.php, this is how contact.php should look like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//if there is any data posted - we should process it
if(!empty($_POST)) {
  //we shall be sending e-mail with data from our php contact form,
  //so let just fill in a message
  $message = '';
 
  foreach($_POST['php_contact_form'] as $name=>$value)
    $message .= $name . ': ' . $value . '<br/>';
 
  $headers  = 'MIME-Version: 1.0' . "rn";
  $headers .= 'Content-type: text/html; charset=utf-8' . "rn";
 
  //now that we have a message from our php contact form
  //we should send it to recipient
  mail('[email protected]', 'New message from our php contact form', $message, $headers);
  echo 'Thank you for contacting us!';
}

Notice: Real contact form should have some form of validation on both client and server side. It should also be protected with (at least) simple php captcha to prevent spam bots from sending a large amount of SPAM mail. However – this is just an example of how PHP contact form can be made for easy handling.