You are here: Home » All Posts » Contact Forms » PHP Contact Form Tutorial

PHP Contact Form Tutorial

in Contact Forms

In this article, we will make a contact form for your website. The contact form contains only the necessary fields required in most contact forms.

The contact form needs to have two parts: the client side ‘front end’ of the form and the server side ‘back end’ of the form. The client side of the form is coded in HTML (actually, XHTML 1.0 strict to be exact) plus some style (CSS) and JavaScript.

Download the code

Download the contact form code here. You can download the form that best fits your needs. Each of the download below contains a different contact form with some variations. See the ReadMe.txt (in the downloaded zip file) for installation instructions.

simple contact form
Minimal contact form with three fields: Name, Email and Message
Try the DemoDownload
contact form with image captcha
Contact form with CAPTCHA
Try the DemoDownload
contact form with file upload
Contact form with File Upload.
There is a file upload field to attach a photo.
The upload is validated (file type, size) and is attached to the form submission email.
Try the DemoDownload
contact form with conditional email
Contact form that emails based on a condition
The form submission is sent conditionally to an address based on the selection in ‘Query Type’.
Try the DemoDownload

The HTML code of the form

Here is the HTML front-end of the form.

<form id='contactus' method='post'>
<fieldset>
<legend>Contact us</legend>

<input type='hidden' name='submitted' id='submitted' value='1'/>

    <label for='name' >Your Full Name*: </label><br/>
    <input type='text' name='name' id='name'  maxlength="50" /><br/>

    <label for='email' >Email Address*:</label><br/>
    <input type='text' name='email' id='email' maxlength="50" /><br/>

    <label for='phone' >Phone Number:</label><br/>
    <input type='text' name='phone' id='phone' maxlength="15" /><br/>

    <label for='message' >Message:</label><br/>
    <textarea rows="10" cols="50" name='message' id='message'> </textarea>

    <input type='submit' name='Submit' value='Submit' />

</fieldset>
</form>

This is a simplified version of the contact form code. (The actual code in the download above has some more elements for better style and security). The HTML code for the form is in the contactform.php file.

The ‘label’ tag describes the input element to the user. The ‘for’ attribute associates the label with the corresponding input element.

Each of the input element has a ‘name’ and an ‘id’ attribute. The ‘name’ attribute is used to identify the value in the server-side script.

The fieldset tag is used to group the elements together. The ‘legend’ tag gives a caption to the ‘fieldset’.

Small textboxes are created using the ‘input’ tag with type=’text’ attribute. The large text area for the message is created using the ‘textarea’ tag.

Finally, the ‘input’ with type=’submit’ creates the submit button.

Input Validations

Input validations are essential for an web form. Validations using Javascript provides immediate feedback to the user. Please note, however, that server side validations should not be avoided.

For the validations in this contact form, we will use the Javascript form validation script from JavaScript-coder.com. Using this script, it is really easy to add client side validations.

Here is the client-side validation code:

<script type='text/javascript' src='scripts/gen_validatorv31.js'>

<script type='text/javascript'>
// <![CDATA[

    var frmvalidator  = new Validator("contactus");
    frmvalidator.EnableOnPageErrorDisplay();
    frmvalidator.EnableMsgsTogether();
    frmvalidator.addValidation("name","req","Please provide your name");

    frmvalidator.addValidation("email","req",
                "Please provide your email address");

    frmvalidator.addValidation("email","email",
                "Please provide a valid email address");

    frmvalidator.addValidation("message","maxlen=2048",
                "The message is too long!(more than 2KB!)");

// ]]>
</script>

The first line includes the main JavaScript validation script. Then the Validator() object is created and initialized. The addValidation() calls adds validation for each element in the form For more information on the validation descriptors, see the documentation.

Server side processing

The server side (back-end) processing is done using the free PHP script: fgcontactform.php. Here is the server side form processing code:

<?PHP

require_once("./include/fgcontactform.php");

$formproc = new FGContactForm();

//1. Add your email address here.
//You can add more than one recipients.
$formproc->AddRecipient('yourname@your-website.com'); //<<---Put your
                                                          //email address here

//2. For better security. Get a random string from
// this link: http://tinyurl.com/randstr
// and put it here
$formproc->SetFormRandomKey('gkEFthfv6gvGAuL');

if(isset($_POST['submitted']))
{
   if($formproc->ProcessForm())
   {
        $formproc->RedirectToURL("thank-you.html");
   }
}

?>

First, we include the fgcontactform.php file. Then, we create an instance of FGContactForm() and add the recipient addresses. Make sure you edit the file ‘contactform.php’ and change the email address to yours!.

The ProcessForm() function does all the work (validates and sanitizes the form submission data and sends the email )

For better security of the form, we use a FormID parameter. The FormID is generated runtime and is unique for each visitor. While submitting the form, we verify the FormID value. This is one step in preventing automated bots from submitting the form.

We have to add a form ID hidden attribute to the form.

Inside the script


You can open the script ‘fgcontactform.php’ in the folder ‘include’ to see the inside working of the contact form script.(although you will rarely need to open the script). Here is the code for the ProcessForm() function.

function ProcessForm()
 {
     if(!isset($_POST['submitted']))
     {
        return false;
     }
     if(!$this->Validate())
     {
         $this->error_message = implode('<br/>',$this->errors);
         return false;
     }
     $this->CollectData();

     $ret = $this->SendFormSubmission();

     return $ret;
 }

As the sequence indicates, first we validate the submission, Collect the data and sends the form submission email.
The Validate() function validates the input values. Name and email are mandatory fields. See the Validate() function for details.

The SendFormSubmission() function composes the form mail and sends the email. We use the PHPMailer email class to send HTML emails.

Customizing the form

You can customize the style of the form by editing the contact.css file. You can add more fields to the form. The field values will automatically be included in the form submission email.

Be Sociable, Share!
Peter Otto January 25, 2012 at 11:23 pm

Thank you,

Easy to implement, looks great. Nice piece of code!

Regards,
Peter

lim January 31, 2012 at 8:01 am

hello

works great

is there anyway to add a BCC email address to the form function??

what code would be required,

many thanks

lim.

Ben February 23, 2012 at 2:30 pm

This is a great script – thanks.
Is there any quick way to trigger a loading gif on a successful submission
(this would be v.useful for the image uploader)?

Joe February 23, 2012 at 2:43 pm

Thanks! Truth be told I have never been all to fond of PHP. It has always seemed clumsy and tedious. This form was a breath of fresh air. It did not require a PHD in rocket science to figure out and it was simple to customize. Cant say enough about how much I like this form!

Justin February 26, 2012 at 5:15 am

Hey,
Nice form, but in the form with captcha (the second one to download), everything works except the captcha image. It doesn’t appear. It just say’s Captcha Image in that spot.
any suggestions?

George March 9, 2012 at 9:32 am

Thanks lots. Stuff works great.

Beth March 12, 2012 at 11:08 pm

Hi – I love these forms, work well and easy to follow.

Justin – could it be your file path to the image isn’t right – make sure you have saved it and then pointed to the right directory?

Henry March 24, 2012 at 2:01 pm

Thanks for this –

The form that I downloaded doesn’t seem to have a phone number field…how would this be added?

Beth March 24, 2012 at 11:41 pm

How can I use the exact same forms and layouts with captcha etc but using SMTP authentication please?

Thanks

Comments on this entry are closed.

Previous post:

Next post: