PHP Contact Form Tutorial

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.

Also see: more free, modern contact forms from

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'>
<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' />


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 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.addValidation("name","req","Please provide your name");

                "Please provide your email address");

                "Please provide a valid email address");

                "The message is too long!(more than 2KB!)");

// ]]>

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:



$formproc = new FGContactForm();

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

//2. For better security. Get a random string from
// this link:
// and put it here



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()
        return false;
         $this->error_message = implode('<br/>',$this->errors);
         return false;

     $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.

Comments on this entry are closed.

  • You guys are geniuses! Seriously, OK, here is my issue OR what I am looking for, anyone want to offer advice, I am open.
    I need to create a form with the following fields. I would ideally like them in the same area on the page as follows:
    ROW 1                      |                    ROW 2                    ]                    ROW 3
    Row 1 would have 6 lines, row 2 would have 6 lines and row 3 would have a radio section and below a comments area.
    My question is has anyone seen any good contact forms set up this way?

  • Thank you so much for sharing this script! This is EXACTLY what I was looking for and actually even better! Thanks again!

  • Hey! This script has been working great for us until recently! All of a sudden the submission forms are taking days to reach our inbox.  Is this normal or is there a way to fix the problem?  Please let me know!

    • Should be a problem in the email server part. Get help from your server admin guys

      • We are just using a google email address and now the forms aren’t coming in at all. We know they are filling them out bc our form leads to a check out page and we are getting peoples checkout information! It doesn’t make any sense and we haven’t changed our code or anything.  Is there someone I could call for help!

        • Great news, I fixed it and it had nothing to do with the great code! For others who run into this problem, if you are hosting with godaddy do not forward your forms to a free email account (like gmail or yahoo) They recently decided not to let those emails through. Ours worked for about three months and then slowly stopped coming in as traffic to the site picked up. It can cause a lot of annoyance.

          • hi meredith,

            how did you get around not using a gmail etc account, did you just use the domain email? Sorry if this questions sounds dumb, am a newbie lol

  • Hi,
    This is a really great tutorial for someone like me who is new to php. Thank you so very much. Just one quick question, how can I get the confirmation message to display on the same page instead of being redirected to thank-you.html?
    Any help will be greatly appreciated.
    Kind Regards

  • Man, thank you very much for your form. It is the first one that really works.
    Well i have also a question: how can i add more e-mail adresses?
    I understood where it should be, but more exactlely?
    I have like this:
    “//1. Add your email address here.
    //You can add more than one receipients.
    $formproc->AddRecipient(‘’); //<<—Put your email address here”
    Where can i add the other e-email adresses?
    Like this?
    or like this?
    Thank you in advance! Hope you can help me. I do not have knowledges in programming, only litlle in html and csc, enought to make a small website.

    • Like this:

      • Ty again! All the best!

  • Thank you for sharing.
    i am still get no luck for my contact form. Could you give me some guide via email or I send my html script from my site ?
    Would you please ?

  • I have to have the from address coming from an e-mail in my domain, so how do I change the from address in the php and specify an additional reply-to address?

    • search for nobody@ in the script files and replace it by your email

  • I am new to PHP.  Could someone please tell me if the form “LABEL” will show up in the recipient’s email even if it is not a required field and the form user leaves it blank?  If not, I need this to happen, and could someone please share how/where I would code that in the PHP?  Thank you!

    • if you create a form field with the name ‘LABEL’ it is going to show up in the mail. If at least it’s not disabled.

  • I am a newbie.

    What server would you advise and how do you add the codes on the server?

    Looking forward to your reply.

  • hi friend,
    Thank you very much.
    very help full article.

  • Hi,

    I installed your code but I get the below error…

    Warning: date(): It is not safe to rely on the system’s timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected ‘America/New_York’ for ‘-5.0/no DST’ instead in C:\Users\AWM\Documents\AWM Files\AWM\WebHome\htdocs\contactformtest1\include\class.phpmailer.php on line 1612 Warning: date(): It is not safe to rely on the system’s timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected ‘America/New_York’ for ‘-5.0/no DST’ instead in C:\Users\AWM\Documents\AWM Files\AWM\WebHome\htdocs\contactformtest1\include\class.phpmailer.php on line 1616

    This is the code it is referring to…Is there a fix I can do?? Thanks!
    * Returns the proper RFC 822 formatted date.
    * @access private
    * @return string
    function RFCDate() {
    $tz = date(‘Z’);
    $tzs = ($tz < 0) ? '-' : '+';
    $tz = abs($tz);
    $tz = (int)($tz/3600)*100 + ($tz%3600)/60;
    $result = sprintf("%s %s%04d", date('D, j M Y H:i:s'), $tzs, $tz);

    return $result;

  • hello.. my question is how can I upload video files… I mean

    should I put another field for video upload or just add the extention name as in the code line… so like this:




    Thank you in advice 🙂 and Im sorry for may horrible english

  • Is there an option to add the email which has been used in the form field to the reciepents? For example something like:


    If not, can i define it somewhere else in the code, instead of calling to the emails filled in the head section?

  • Using: Contact form with CAPTCHA

    Getting error using downloaded files.

    Fatal error: Call to undefined function mb_substr() in E:\kunden\homepages\11\d369629443\www\contact\include\captcha-creator.php on line 133

    I haven’t altered the captcha-creator.php in any way. The only form I updated was the contactform.php to reflect the correct email address and followed the link to generate the random code as directed.

  • How do I make the recipients variable?

    Tried this, but doesn’t work.


    Any help please?

  • Hi, I am using ‘Contact form with CAPTCHA’
    I want to add one cc and two bcc email ids.
    How can I add these?


  • I see (per the reply to another question) how to add a second email, but how do I set it for a specific variable?

    For instance, I want a general contact email to go to and a request for marketing to go to The person filling out the contact form will need to select who they are contacting via a dropdown or button select option. Thanks for the help! Love the script!

  • I tried to use this code and got the following error message:

    Deprecated: Function eregi() is deprecated in /var/www/dunn/simple-form-1-1/include/fgcontactform.php on line 548 Call Stack: 0.0002 345960 1. {main}() /var/www/dunn/simple-form-1-1/contactform.php:0 0.0045 961732 2. FGContactForm->ProcessForm() /var/www/dunn/simple-form-1-1/contactform.php:26 0.0045 961732 3. FGContactForm->Validate() /var/www/dunn/simple-form-1-1/include/fgcontactform.php:129 0.0046 961776 4. FGContactForm->validate_email() /var/www/dunn/simple-form-1-1/include/fgcontactform.php:387 Deprecated: Function split() is deprecated in /var/www/dunn/simple-form-1-1/include/class.phpmailer.php on line 470 Call Stack: 0.0002 345960 1. {main}() /var/www/dunn/simple-form-1-1/contactform.php:0 0.0045 961732 2. FGContactForm->ProcessForm() /var/www/dunn/simple-form-1-1/contactform.php:26 0.0047 961928 3. FGContactForm->SendFormSubmission() /var/www/dunn/simple-form-1-1/include/fgcontactform.php:136 0.0051 964456 4. PHPMailer->Send() /var/www/dunn/simple-form-1-1/include/fgcontactform.php:194 0.0057 967352 5. PHPMailer->MailSend() /var/www/dunn/simple-form-1-1/include/class.phpmailer.php:413

    Is there a fix?

  • Hi
    I am not sure what the instructions mean when it says

    2. Upload the entire folder to your web site. can you please clarify.

    • upload the entire content of the folder from the download link to your website, or create a folder in your FTP and upload the entire contents in there so that you can check first if it is working.

  • I’ve tried a lot of contact forms available, none of them works until I found this one. thanks so much for helping the non programmer people. more blessing to you man!