If this tutorial is not what you were looking for, you still have any questions, suggestions or concerns - feel free to let us know. Please help us to serve you better!

Your Name

Your Email

Your Message (required)

captcha

How to create a contact form in HTML

This tutorial will teach you how to create a very simple contact form for HTML based website template.

First of all create 2 files: contact_form.html and contact.php. The first file will contain HTML code for the form and the second -will process the data from the form


HTML

Below is the HTML code of the contact form

<form action="contact.php" method="post">
	Your name
<input type="text" name="cf_name">
Your e-mail
<input type="text" name="cf_email">
Message
<textarea name="cf_message">
<input type="submit" value="Send"> <input type="reset" value="Clear"> </form>

And this is how it will look in the browser

HTML contact form

Let’s have a quick look at some main aspects of it. The <form> tag should have 2 additional attributes:

action=”contact.php” – this attribute specifies where to send the data from the contact form fields, when it has been submitted

method=”post” – this attribute specifies how to send data from the form to the file specified in the action attribute

The <input> and <textarea> tags should have an attribute “name” with a unique identifier. This attribute is used to identify form data after it has been submitted to the server
And the 2 input elements that are used as Submit and Clear buttons, one should have type=”submit” assigned to it and the other type=”reset”

That’s basically it. As easy as it looks

PHP

Now for the contact.php file that will actually grab the data from the fields, compose into a message and send to your email. You can download contact.php file from this link. Below is the code of the file with comments to its major sections.

Assigning the data sent from the contact form fields (cf_name, cf_email, cf_message) to php variables ($cf_message, $field_email, $field_message)

$field_name = $_POST['cf_name'];
$field_email = $_POST['cf_email'];
$field_message = $_POST['cf_message'];

$mail_to shall contain the site owner email, this is where the email is sent to. You can specify multiple emails by separating them with a comma (e.g. [email protected], [email protected])

$mail_to = 'test@test-mail.com';

Subject of the email you receive from the contact form

$subject = 'Message from a site visitor ' . $field_name;

Constructing the body of the message

$body_message = 'From: '.$field_name."\n";
$body_message .= 'E-mail: '.$field_email."\n";
$body_message .= 'Message: '.$field_message;

Constructing the headers of the message

$headers = "From: $cf_email\r\n";
$headers .= "Reply-To: $cf_email\r\n";

Defining mail() function and assigning it to a variable $mail_status, which is used below to check whether the mail has been sent or not

$mail_status = mail($mail_to, $subject, $body_message, $headers);

If the mail() function executed successfully then do the code below

if ($mail_status) { ?>
<script language="javascript" type="text/javascript">
// Print a message
alert('Thank you for the message. We will contact you shortly.');
// Redirect to some page of the site. You can also specify full URL, e.g. http://template-help.com
window.location = 'contact_page.html';
</script>
<?php
}

If the mail() function fails, then execute the following code

else { ?>
<script language="javascript" type="text/javascript">
// Print a message
alert('Message failed. Please, send an email to gordon@template-help.com');
// Redirect to some page of the site. You can also specify full URL, e.g. http://template-help.com
window.location = 'contact_page.html';
</script>
<?php
}?>

You can also download compiled contact_form.html and contact.php files in a single package

 

Proceed to the tutorial on how to add fields to the contact form

How to create a contact form in HTML, 2.2 out of 5 based on 15 ratings
  • Aya

    Hello,

    1st thanks,
    When I try this code (how to create a contact form), I got the following error:

    Warning: mail() [function.mail]: Failed to connect to mailserver at “localhost” port 25, verify your “SMTP” and “smtp_port” setting in php.ini or use ini_set() in D:\XAMPP\xampp\htdocs\Own_Work_Comp\Company_Site\contact.php on line 11
    Failure

    • Chris Diaz

      The contact form script can be used only on a live server. You are using it on your local server (XAMP based).

      In order to make it work you need to upload it to the live server (order hosting) or configure mail server on your XAMP localhost

  • http://www.zooqc.com Bill

    Hi

    your tutorial is very easy understand and viable, but I have a question about how to make contact.php when contact form have a drop down selection. thanks if you can have any help.

    Bill

  • somebody

    I used this form and I like that it is simple but I need to make some fields to be “required” how can I do this using this form?

    • Chris Diaz

      The tutorial on how to create required fields will be added in nearest future

      • somebody

        Thanks, could you post the link for that tutorial on a comment here(when that tutorial will be available)?

  • http://dreagoen.jimdo.com Dreagoen

    Hi, after 10 minutes of trials and errors I managed to do that on the host it’s very simple. I don’t even know how do i made errors at all, maybe i’m just don’t pay enough attention. So if someone is failing at doing this, here’s the tip: Read EVERY WORD in this tutorial… And thanks to Gordon for the tutorial.

  • magnus

    Hi. do i need to have installed a mail server on my web server for this to work? I have set it up like its shown in the tutorial, and i get the “tank you for the message i will contact you shortly”, but no mail to the mail to address. Is there something i`m missing. What are the requirements for this form to work?

    • Gordon J. Blair

      Most local servers do not include mail server, so you’ll need to install some additional software for that. Though there are many risks connected with that, so I suggest you test the form on a live server.
      If you don’t have a host and a domain yet, then google for some free hosting providers. There are many on the web and most of them support php mail() function

  • http://ericloomis.webs.com/ eric

    i need a form box that will email back to my email account. I have the box part which it was easy but i can’t email my account to me. Please help me.

  • http://www.theanimeinn.com Jaswant

    Hi,
    The tutorial is very easy. Thanx to gordon.
    But i am facing a problem. When i amsubmitting the form it only prompts “Message failed,please send an email to me”.

    It is not emailing the contents to me.

    Jaswant

    • Gordon J. Blair

      Might be that your server does not support PHP mail() function, so the script fails. Though this also can be some server specific configuration, which does not allow execution of the script. In general this should be investigated on the server side

      • Gordon J. Blair

        Another common problem is that some hosts, require all PHP mails to specify a FROM: and TO: address that is in your own domain.
        E.g. if your site is ww w.mydomain.com then the email you use in the form can be only {some-name}@mydomain.com
        A solution to this would be deleting the $headers variable from the mail(…) function

  • http://godscircle.net Patrick

    Tks just looking ill try it when I get home sounds simple tks again

  • http://writer-base.com/story.php?id=707491#comments Robert Moran

    Great, there are actually some great tips on here that my customers might find this relevant, I will email them a link. Thanks

  • Tom

    When I hit the submit button it takes me to a blank page.

  • http://nobull.com billy

    Awesome! great info.

  • Radczyck

    awesome

  • Fizurro

    hi thats cool
    1.when hit send button so where the data will send n how to make the data directly send to my email?
    2.if i want to put some creative out look box then how i want to use that code?

  • Anonymous

    You can try to use this script:

    window.onload=function(){
    var elForm=document.getElementsByTagName(‘form’)[0]; // Get the first form in the document
    elForm.onsubmit=function()
    {
    var required=['First Name','Last Name','Member Name'];
    // Place in this array the name of the form that you think should be mandatory
    var bool=true; // Create bool variable and set its value to true
    for(var i=0;i<required.length;i++)
    {
    if(document.getElementsByName(required[i])[0].value=='')
    {
    alert(required[i]+' textbox is mandatory to fill in.');
    bool=false;
    }
    }
    return bool;
    }
    }

    I recommend you to search google for “HTML form required field”

  • Anonymous

    Add it to the HTML file

  • Lisa

    Hi. I changed only a few things in the php file and saved both locally to my computer. But when I test it out and fill out the form, it gives me a pop up asking if I want to download or save. What am I doing wrong?
    Thanks.
    Lisa

    • Alex Ross

      Unfortunately, it will not work locally. You should upload it to your hosting server.

  • Josh

    Hi there,

    Is there anyway to make the message box bigger automatically?

    Thanks,
    Josh

    • naz

      I managed to increase the size of the message box by add altering this line:

      cols=”50″ means the width of the box is 50 characters long and rows=”10″ means the height is 10 characters high. hope that helps.

  • Issamht65

    //////////////////////

  • tejinder singh

    thanks alot………..i just downloaded the SINGLE PACKAGE n works on very
    first time

  • Marco

    Thanks for the very useful code.

  • http://komalcrane.com/ escort hydra

    this is awesome code. I was looking for a html form and found your code. thanks a lot

  • David Reilly

    How would I add code that would make certain fields a requirement? Thanks.

    • alex_ross

      you can just add “required” attribute for a needed input:

      required=”required”

      so it will look like:

      <input type=”text” required=”required” />

  • Keypixel

    Yes ! its work ! Thanks for the code !!!!!

  • JB

    What does this require on the server side?

    • alex_ross

      PHP software installed and enabled/configured PHP mail() function.

  • Shane

    you cant add or remove anything to this, so if you want to add say for examples: Website, it doesnt work, only can you have the 3 things as listed. pointless!

  • alex_ross

    the most likely PHP is not installed or you just opened your page with CF

    • Elle

      I’m having the same issue – when you click send, it just opens the php file in the browser. I know PHP is definitely installed. What else could cause this?

      • Alex Ross

        Make sure you are opening .html file with your CF “via server” like by typing: http://localhost/contact.html in the browser address bar. It will not work if you just go to e.g.: AppServwwwcontact.html and open the file.

  • alex_ross

    you need to contact your hosting provider and consult with them.

  • Alex Ross
  • boxon

    I am just a stupid front-end developer, and i dont like to mess with PHP, MySQL and other witchcraft. But sometimes it is really hard to mess with programmers who usualy dont have any social skills at all, and it is easier to do something on my own. After about 50 attempts to make functional and working contact form, I stumbled upon this site, and did it from the first. This is apsolutely best, simplest and clearest tutorial that I have seen on the net in a whyle. Thank you, guys, and feel fre to make more tutorials.

  • Kdembowski

    thaaanks a looooooot.

  • thankful

    Thank you! I’ve only been using PHP for a bit, but this simplified things greatly!

  • http://www.pacquiaobradleytickets.com/ Pacquiao vs Bradley

    Amazing, the form I used before this will send the message to my spam folder but I change the code like above and it works, everytime I do testing, it will go to my inbox. Thanks a lot..

  • Alex Ross

    The most likely the emails are being blocked by your hosting server. Please contact your hosting provider and check the issue with them.

  • KP

    This is the most amazingly post I would have ever seen. I have been through a lot of contact form pages, but always ended up tearing my hair because of their complex scripts and codings. Here, it’s is very easy to understand and working script. Cheers :D

  • Tonyabiyounes

    Big Thanks for your support

  • Ewerew

    great thx

  • http://www.facebook.com/profile.php?id=542029833 Alexis Goovaerts

    nice, perfect!

  • Adetola Sadiku
    • Alex Ross

      The most likely, your SMTP server isn’t open-relay one. Please consult with your hosting provider.

      • Adetola Sadiku

        what kind of question do I need to ask? And when you say hos provider, do you yahoo?

        • Alex Ross

          Unfortunately, I don’t know who is your hosting provider. This is Yahoo as far as I can see.

          • Adetola Sadiku

            Yes, it is Yahoo

          • Alex Ross

            In this case you should contact Yahoo hosting support team directly.

  • Alex Ross

    1) Make sure you have:

    2) Make sure that names of input fields and names of grabbed variables in PHP are the same, e.g.:

    $field_name = $_POST['cf_name'];

    • olya

      thanks! 2) was the issue

  • JeanB

    This code is spam protected?

    • Alex Ross

      Basically no.

  • Rizwansalaam

    Thanks alot for this. Although there are many tutorial’s out there to show you how to create a contact form, none are as concise, a step-by-step way of doing this, (how tutorials should be). I’ve seen complex ways to the bizarre of creating a simple contact form. This truly is simple, and i have limited php knowledge, even i understand what is going on here. Keep up the excellent work.

  • http://twitter.com/Jinjalicious Jinja Bar Bistro

    Fantastic. Thank you!

  • http://twitter.com/devongilchrist Devon Gilchrist

    So sorry, that last comment from Jinja was supposed to be from me (manage too many accounts:) This tut, html code snippet and php download just saved me a lot of time. Thank you!

  • Dan

    THANK YOU SO MUCH!

  • Midhu

    Brilliant Stuff! Loved the way it was explained. Thank you!

  • Alex Ross

    Unfortunately, it will not work locally. You should upload it to your hosting server.

  • Padmanaban Mine

    Nice bady……

  • Alex Ross
  • hugo

    I must thank you for the coding tips. It worked perfectly. Thanks so much my friend, always keep sharing your knowledge!

  • Alex Ross

    Unfortunately, it will not work locally. You should upload it to your hosting server.

  • james

    thank you :)

  • Martin

    Man. THANK YOU. Just THANK YOU. Seriously, this post is 1 in a million.

  • http://www.facebook.com/mmtdutt Tilak Dutt

    in which dir should i place the contact.php file?

    • service2u

      it goes in the same dir as the contact HTML,

  • http://twitter.com/Jessius Jessica Thompson

    This is the most helpful way to create a nice, working contact form I’ve found so far, thank you!

  • http://www.mattnet.99k.org/ Matthew Dewhurst

    I’m new to Php, I was wondering if you need a database for this to work or should it just work with that one Php file and the Html form? Thanks.

    • Alex Ross

      Basically you don’t need a database to make CF work.You just need at least two files .html and .php one.

      • http://www.mattnet.99k.org/ Matthew Dewhurst

        Thanks for the reply, I didn’t actually notice you had replied to my comment until now, I went ahead and used the scripts anyway and it works perfectly, thanks a lot!

  • ramesh b
    • Alex Ross

      Please make sure that your server supports PHP.

  • Remalion

    Outstanding, just what i was looking for. Great job mate.
    Nice and simple. many thanks.

  • paguba

    Hello can anyone tell me why only message its shown in the email sent?…

    in php file i have placed like this:

    $nume = $_POST['nume'];
    $email = $_POST['email'];
    $mesaj = $_POST['mesage'];

    $mail_to = ‘exemple@m[email protected]’;
    $subject = ‘Mesaj de la un vizitator ‘.$nume;

    $body_message .= ‘E-mail: ‘.$email.”n”;
    $body_message .= ‘Mesaj: ‘.$mesaj;

    $headers = ‘De la: ‘.$email.”rn”;

    $mail_status = mail($mail_to, $subject, $body_message, $headers);

    and in html file i placed like this:

    Nume :

    Email :

    Mesaj :
    mesaj

    so when i recieving mail ..i can see only message..but $body_message .= ‘E-mail: ‘.$email.”n”; and $headers = ‘De la: ‘.$email.”rn”; i can’t see it…where i’m doing wrong?please help me.

    Thx in advance.

    • Alex Ross

      Your name and email fields in HTML should have attributes “name” with the corresponding values: nume and email

  • asif

    supper post this is helpful post.
    Live Technology

  • Sammy Kumar

    So simple thanks!

  • http://www.99th.in/ 99th Packers

    Very useful information. Thank you for sharing
    it. Thanks 99th

  • Carlton Stith

    This form worked great. Thanks!

  • Jennifer Booth

    This is fantastic – thank you for simplifying my life! Quick question though – how do I increase the size of the input fields? I know it has to do with character count, but I’m not sure how/where to do it. Thanks!

  • Luke

    Thanks alot. This is brilliant. :) Been trying to do this for so long.

  • Dimitri Fox

    Dimitri Fox

    worked fine for me.thank you

  • Preetham

    Does it work with local system?

    • Alex Ross

      Unfortunately, no.