Howto: Make a contact form and mail the details with PhP

I keep seeing the same request on forum’s day in day out.

This has to be one of the most documented features of PhP however people still have problems with it…

Here is my attempt at helping to make a “contact us form” on your website.

– A php enabled webserver.
– PHP configured with a mailserver ( to send mail through ) , Most servers will already be setup.. So give it a try if you don’t know the answer to this.
– A text editor / html editor ( to create your .php files. )
– An basic understanding on html and php and how they work together.
– ~10minutes of your time.

We are about to make a contact us form using html and php.
We will create one file, Called contact_us.php
This file will handle the form and the actual sending of emails.

See code comments on how it works..

Paste the below into a text editor and save it as contact_us.php.
Once uploaded to your web-server, Just load the page and viola, It ? *should*? work.

if ($_POST["email"]<>'') { 
	$ToEmail = ''; 
	$EmailSubject = 'Site contact form '; 
	$mailheader = "From: ".$_POST["email"]."\r\n"; 
	$mailheader .= "Reply-To: ".$_POST["email"]."\r\n"; 
	$mailheader .= "Content-type: text/html; charset=iso-8859-1\r\n"; 
	$MESSAGE_BODY = "Name: ".$_POST["name"]."<br>"; 
	$MESSAGE_BODY .= "Email: ".$_POST["email"]."<br>"; 
	$MESSAGE_BODY .= "Comment: ".nl2br($_POST["comment"])."<br>"; 
	mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader) or die ("Failure to send email"); 
Your message was sent
} else { 
<form action="contact_us.php" method="post">
<table width="400" border="0" cellspacing="2" cellpadding="0">
<td width="29%" class="bodytext">Your name:</td>
<td width="71%"><input name="name" type="text" id="name" size="32"></td>
<td class="bodytext">Email address:</td>
<td><input name="email" type="text" id="email" size="32"></td>
<td class="bodytext">Comment:</td>
<td><textarea name="comment" cols="45" rows="6" id="comment" class="bodytext"></textarea></td>
<td class="bodytext">&nbsp;</td>
<td align="left" valign="top"><input type="submit" name="Submit" value="Send"></td>

Comments are closed.