PHP Contact Form

June 28, 2007

All, Forms, Freebies, PHP

PHP Contact Form Script

Article written by Jeeremie

Here is a nice contact form for your website.

This contact form will return a validation message if the message was sent succesfully.
It will also display an error message if you try to send an empty message or if the e-mail is invalid.

Preview / Download

DemoDownload(9.6 KiB, 45,114 hits)

There are only two scripts for this simple contact form:

  • contact.php : the PHP contact form itself (contact.php)
  • style.css : the CSS page (style.css) to control the layout of the page

The Author

Article written by Jeeremie:

Hi, My Name is Jeremie Tisseau. I am a French UI/UX Designer, Event Organizer and Web Entrepreneur based in Bangkok, Thailand, since January 2009. I design beautiful and functional web and mobile apps for early stage startups.

Tweet

Want to become a guest author on this blog?

64 Comments

  1. Ad o Braga says:

    30 Jun, 2007

    I tested you script.
    http://www.holistica.com.br/artigo1/contato/contact.php

    But my internet provider don t send the messagen for my inbox. Look, message the CONGRATULATION, but don t.

    Very Good.

  2. darlene says:

    1 Jul, 2007

    great site for helping people!!…wtg

  3. Jeremie Tisseau says:

    2 Jul, 2007

    Hello Adao Braga,

    I tested the contact form you installed on your server but I can t see what is the problem. Did you changed the email address to be your own in the contact.php page (user@email.com - line 61)? If it is not working, try changing the email to be something else or contact your internet provider. And by the way, check your spam box. It is possible your email provider moved the mail into it.

    I hope it helps you.

  4. tamara says:

    10 Jul, 2007

    is this good for a flash form ?
    my form in flash gives me a message of message sent but i get no emails

  5. Jeremie Tisseau says:

    10 Jul, 2007

    Hello Tamara,

    I have no idea. I never tried to adapt it to a flash form but I suppose it is possible.

    However, your problem may due to your e-mail provider. Try to contact them and see if they can first fix it. If not, then it could be a problem with your flash form.

    Let me know.

  6. Anwar says:

    28 Jan, 2008

    Hey, PHP guy!
    I am getting this problem,
    Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in C:Program FilesEasyPHP 2.0b1wwwShop On!categories.php on line 68
    I know there is some problem with the mySQL. But EasyPHP is showing it to me as started.
    I have the database in the MYsQL data folder as well. Do you have any idea, what might be the problem ?
    P.S. plz reply on my email adress! Thanks

  7. shivu says:

    31 Jul, 2008

    great site for helping people

  8. ollie10123 says:

    1 Aug, 2008

    Hey, Any plans for expanding the form to include SMTP authenitcation?

    Ollie

  9. Jeremie Tisseau says:

    1 Aug, 2008

    No, not at the moment but that s a good idea Ollie. I will think about it. Thanks!

  10. Jason says:

    2 Aug, 2008

    Hey Jeremie Tisseau,

    I know this form is free and so any advice would be greatly appreciated, but understand if you don t have time to look at it.

    I love this form and am using it a lot but I ve come across a need for some drop down select menus. Which it works fine and collects the data and emails it, the problem comes in if there is any type of error, the drop-down select menus RESET because there is no way to tell them what the original value was that had been selected by the user.

    I ve tried several things without success. Thought you might have some advice to make this work. (I sent you an email with the code if you want to look at it).

    Thanks, the site looks AWESOME!!! BTW, FYI, MooFlow works in Firefox 3+ guess I was behind the times =)

    j

  11. Jeremie Tisseau says:

    2 Aug, 2008

    Thanks Jason,

    I got your email two days ago but I didn t have time to look at it yet. I will as soon as possible.

  12. Jason says:

    5 Aug, 2008

    Hey man, no problem, I just appreciate it! Hope things are going great.

  13. Jeremie Tisseau says:

    5 Aug, 2008

    Jason,

    Your code was correct. Just replace:

    1
    2
    3
    4
    
    else if(trim($referred) == '')
    {
    $error = '<div class="errormsg">Please tell us who referred you to us. Thank You!</div>';
    }

    …by:

    1
    2
    3
    4
    
    else if(trim($referred) == '(Please Select One...)')
    {
    $error = '<div class="errormsg">Please tell us who referred you to us. Thank You!</div>';
    }

    And it should work! you can download the (simplified) code here if you want.

  14. Jeremie Tisseau says:

    5 Aug, 2008

    By the way, I will release in a couple of weeks the quote form I used on my old site. It was based on this contact form. Since I am not using it anymore, I think it is a good idea to give it away. I will publish it in approximately one month as I have other posts in the queue waiting to be published.

  15. Jason says:

    8 Aug, 2008

    Hey Jeremie Tisseau,

    Thanks for looking at it. I got it to require it so that if it s not selected it gives an error, but the problem remains that if any error happens, then the select box doesn t remember what was selected and reset itself back to the default… does that make sense?

    Sorry if I was not more clear. I really appreciate your time.

  16. Jeremie Tisseau says:

    8 Aug, 2008

    I tried this and it works! Check it by yourself (click on [+] to expand the code) :

    ?Download download.txt
    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
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
     
    <html xmlns="http://www.w3.org/1999/xhtml">
     
    <head>
      <title>test SELECT</title>
    <style type="text/css">
    /*<![CDATA[*/
    .errormsg {
    	color: red;
    	border: red 1px solid;
    	padding: 3px 7px;
    	margin: 20px 5px;
    }
     
    /*]]>*/
    </style>
    </head>
    <body>
    <!-- The contact form starts from here-->
    <?php
    	$name       = '';
    	$Email       = '';
    	$error     = ''; // error message
     
    	// Select
    	function select_options($option_values, $default_option){
    		foreach ($option_values as $value => $text)
    		{
    			$is_selected = ($value == $default_option)? 'selected': '';
    			$html_text = htmlspecialchars($text);  // in case text contains '&', etc.
    			echo "<option value="$value" $is_selected>$html_text</option>n";
    		}
    	}  // End Select
     
    	// Start Arrays for Select inputs
    	$select1 = array('' => '', 'test1' => 'test1', 'test2' => 'test2');
    	$select2 = array('' => '', 'pizza' => 'pizza', 'noodles' => 'noodles');
     
     
    	if(isset($_POST['send']))
    	{
    		$name   = $_POST['name'];
    		$Email   = $_POST['Email'];
    		// Start Arrays for Select inputs
    		$Select_1 = $_POST['select1'];
    		$Select_2 = $_POST['select2'];
     
     
    		if(trim($name) =='')
    		{
    			$error = '<div class="errormsg">Enter your Name please!</div>';
    		}
     
    		else if(trim($Email) == '')
    		{
    			$error = '<div class="errormsg">Please enter your email address!</div>';
    		}
     
    		else if(!isEmail($Email))
    		{
    			$error = '<div class="errormsg">You have enter an invalid e-mail address. Please, try again!</div>';
    		}
     
    		else if(trim($Select_1) == '' )
    		{
    			$error = '<div class="errormsg">Please choose an option for "Select - test 1". Thank You!</div>';
    		}
     
    		else if(trim($Select_2) == '' )
    		{
    			$error = '<div class="errormsg">Please choose an option for "Select - test 2". Thank You!</div>';
    		}
    		if($error == '')
    		{
    			if(get_magic_quotes_gpc())
    			{
    				$message = stripslashes($message);
    			}
    			//CHANGE EMAIL ADDRESS !!!!
    			$to      = "test@gmail.com";
    			$subject = '[WEBSITE] : ';
    			$msg     = "Name :" . $name;
    			$msg     .= "rnEmail :" . $Email;
    			$msg     .= "rnSelect - test 1 :" . $_POST['select1'];
    			$msg     .= "rnSelect - test 2 :" . $_POST['select2'];
    			mail($to, $subject, $msg);
    ?>
     
    <!-- Message sent! (change the text below as you wish)-->
    <h1>Congratulations!!</h1>
    <p>Thank you <?=$name;?>, your message is sent!</p>
    <!--End Message Sent-->
     
    <?php }
    } if(!isset($_POST['send']) || $error != '') {
    ?>
     
    <!--Error Message-->
    <?=$error;?>
     
    <form  method="post" name="contFrm" id="contFrm" action="">
     
    	<div><label>Your Full Name: <span class="required">*</span></label> </div>
    	<input type="text" size="40" value="<?=$name;?>" name="name" id="name" />
     
    	<div><label>Your Email: <span class="required">*</span></label> </div>
    	<input type="text" size="40" value="<?=$Email;?>" name="Email" id="Email"  />
     
    	<div><label><span class="required">*</span> Select - test 1:</label> </div>
    	<select name="select1" id="select1">
    		<?= select_options($select1, $_POST['select1']) ?>
    	</select>
     
    	<div><label><span class="required">*</span> Select - test 2:</label> </div>
    	<select name="select2" id="select2">
    		<?= select_options($select2, $_POST['select2']) ?>
    	</select>
     
    	<p></p>
    	<!-- Submit Button-->  
    	<input name="send" type="submit" class="button" id="send" value="Submit" />
     
    </form>
     
    <!-- E-mail verification. Do not edit -->
    <?php
    }
    function isEmail($email)
    {
    return(preg_match("/^[-_.[:alnum:]]+@((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]]).)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]).){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
    }
    ?>
    </body>
    </html>
  17. Jeremie Tisseau says:

    8 Aug, 2008

    By the way, if you want to validate a phone number in your PHP contact form, add this code:

    1
    2
    3
    4
    5
    6
    7
    8
    
    else if(trim($phone) == '')
    {
      $error = '<div class="errormsg">Please enter your phone number!</div>';
    }
    else if(!preg_match("/^[0-9]{6,}$/",$phone))
    {
      $error = '<div class="errormsg">Please enter a valid phone number!</div>';
    }

    … like this: (click on [+] to expand the code)

    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
    
    if(trim($name) == '')
    {
      $error = '<div class="errormsg">Please enter your name!</div>';
    }
    else if(trim($phone) == '')
    {
      $error = '<div class="errormsg">Please enter your phone number!</div>';
    }
    else if(!preg_match("/^[0-9]{6,}$/",$phone))
    {
      $error = '<div class="errormsg">Please enter a valid phone number!</div>';
    }
    else if(trim($email) == '')
    {
      $error = '<div class="errormsg">Please enter your email address!</div>';
    }
    else if(!isEmail($email))
    {
      $error = '<div class="errormsg">You have enter an invalid e-mail address. Please, try again!</div>';
    }
    if($error == '')
    {
      if(get_magic_quotes_gpc())
      {
        $message = stripslashes($message);
      }
    ...

    The code “/^[0-9]{6,}$/” will check if the phone number contains only numbers ([0-9]) and if the number contains at least 6 characters ({6,}). You can increase this number if you want. For example, in Spain, phone numbers contains at least 9 numbers. Your code could be: “/^[0-9]{9,}$/”.

  18. Jason says:

    8 Aug, 2008

    DUDE, did you re-write the entire form?? OH MY GOODNESS!!! I m so so sorry. I just thought it might be a quick fix. I did not mean for you to have to do all that work.

    Nevertheless it works AWESOME!!!! Perfect. You should upload it as a download as a NEW form with your other two because it s completely different in a lot of ways =)

    THANKS!!!!!!!!!!

  19. Jeremie Tisseau says:

    8 Aug, 2008

    You are welcome Jason. I enjoyed it anyway!

  20. mohd saif says:

    20 Aug, 2008

    hi,
    the problem statement for comment number 6 of anwar is:
    please check your connection variable and the database variables in the mysql_connect and mysql_select_db.

  21. Navin says:

    4 Oct, 2008

    Hi Jeremie Tisseau,

    what a piece of simple php script, its a best one i came across.

    Can you please tell me how can i add drop down box to your wonderful script which should include in mail

    dropdown1 : Date
    dropdown2 : month
    dropdown3 : year

    please help me its important to me.

  22. Obzolete says:

    4 Nov, 2008

    I just get this errormessage:

    The POST method has been disabled by the server administrator

  23. Jeremie Tisseau says:

    4 Nov, 2008

    Maybe your host does not allow to send messages with the post method. Contact your host and ask them.

  24. Mohamed says:

    12 Dec, 2008

    Hello,

    Let me thank you for this nice contact form.

    For those who needs drop downs, I added Jeremie Tisseau s code to the original. you can download it here until Jeremie Tisseau updates his version.

  25. Jeremie Tisseau says:

    12 Dec, 2008

    Thanks Mohamed. Great work!

    Anyone, if you need a more complex form, you can download my free quote form on my freebies page. It has some drop down menus, radio buttons and so on.

  26. Mohamed says:

    15 Dec, 2008

    I have added a captcha protection to the contact form instead of the 2+3 problem. download from here.

    • Sandra says:

      28 Dec, 2012

      I know its been a while…
      This works like charm but when I tried the captcha that Mohammed insert, it just keep telling “Please type the text in the picture exactly as you see it.”

      Negither I can make the Phone validation work.

      Any idea?

  27. Pete says:

    8 Feb, 2009

    post #16 is good the error checking is in order and the select box works great (i have not been able to do that before i found this script) i have customized the error messages, well as opposed to messages the text / textbox border goes red and i have removed the else if s for the error check and replace with standard if so it does all the checking at once useing an array and got that fine, however i would appreciate help with a very lightweight captcha script (4 or 5 letters / numbers long NOT case sensitive and ability to change the bg / text colour but must be a very small image size (kb s) could you help ?

  28. Steve Clay says:

    6 Mar, 2009

    Do not use this script. It is vulnerable to e-mail header injection (allows an attacker to send spam from your hosting account) and XSS (allows a 3rd party site to steal your users cookies). This is one of the few “free” contact forms that isn t full of holes.

  29. Steve Clay says:

    6 Mar, 2009

    I apologize if I was a little harsh, but PHP security is very important, especially if your encouraging others to use the code. I highly recommend this book. I should also mention your WordPress templates are beautiful.

    • Jeremie Tisseau says:

      6 Mar, 2009

      No problem. Thanks for letting us know. I actually didn t know.

  30. tonton says:

    13 Apr, 2009

    super work fine

  31. Chris Kalis says:

    1 Jun, 2009

    Hi Jeremie Tisseau,

    So is this still a safe form to use? I m trying to get this into a website but I can t seem to get it to work after I press send. Maybe it s because that I m using it with spry and it jumps/ slide back to “home” from “contact”. So I have to click on “contact” again and it display the msg, “congratulation… “. It does not stay at “contact” after send. It ll be greatly appreciated. Thanks for your time.

  32. Amir says:

    19 Sep, 2009

    Hi
    I was testing the form and I noticed the first error message is Please enter a subject!

    Is there any reason the Subject error message showing up first and not Name? and how would I change the order?

  33. Alexis says:

    30 Sep, 2009

    Saludos des de Lima Peru gracias por el Php de contactos lo voya meter en mi web

  34. Beho says:

    11 Mar, 2010

    Hello,
    I want to use this form but just the email!!!
    I mean something like,
    Please, enter your email : xxxxx
    2 + 3 = xxxxx

    That s it, I tried but It didn t work, I am not an expert in php coding,

    Thanks in advance man,
    Beho

  35. Francisco says:

    30 Aug, 2010

    hello,
    I was wondering if in your form, you can add some code to redirect to a thank you page, rather than leave the text message “congratulations”
    if this can be …
    What code should I add? And where?

  36. Enrique says:

    3 Nov, 2010

    Gracias hombre!!!

    Thank men!!!

  37. Sunny says:

    28 Nov, 2010

    I get the following error after changing my email to

    Warning: mail() [function.mail]: SMTP server response: 451 See http://pobox.com/~djb/docs/smtplf.html. in D:Hosting6703244htmlContactFormindex.php on line 93

    any suggestions?

  38. Mark says:

    16 Jan, 2011

    Hi
    I was testing the form and I noticed the first error message is Please enter a subject!

    Is there any reason the Subject error message showing up first and not Name? and how would I change the order?

  39. Eric Hamby says:

    11 Feb, 2011

    When i press submit it goes to a 404

  40. Geronimo says:

    9 Apr, 2011

    INGLES
    The form works fine. Congratulations.

    Question. Where I can put a CCO

    What is oden and where to send the mail with Bcc.

    ESPA OL
    El formulario funciona muy bien. Felicitaciones.

    Pregunta. Donde puedo colocar una CCO

    Cual es la oden y el lugar para que envie el mail con copia oculta.

  41. Dan says:

    12 May, 2011

    Hi Jeremie, Great form! thank you for sharing it.
    I have a question, is it possible for the form to be sent to the user who is inputting the question? so they get a copy of it?

    Also my form seems to be emailing me twice? do you know why?
    Thank you and I look forward to hearing from you.
    Regards
    Dan.

  42. Kasia says:

    20 May, 2011

    Hi,
    is this form supports for example the Polish characters?
    I tried to send a message with Polish characters but in the message was only the other stamps.

    Thanks for sharing:)

    • Jeeremie says:

      23 May, 2011

      You might want to change the html charset to something like this to support Polish characters:
      <meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-2″ />

  43. Kasia says:

    23 May, 2011

    Thank you for your reply:)
    I ll check it out today.

    Greetings from Poland :)

  44. Sofi says:

    31 May, 2011

    Hi! I m starting in web development. Tnks for sharing that form. I find it very usefull (was easy and fast to adapt) and help me very much to intruduces me to PHP. I ve used before in a friend s web. Now, I will use this with a SWF form, I wait don t have any trouble, the comments in the code was very helpfull!!! :)

  45. Rub n Dar o says:

    29 Jun, 2011

    Hello, thank you for the saving of time. The form is very good.
    Regards from Ecuador.

  46. Gala says:

    21 Jul, 2011

    Thanks Jeremie!

    Contact form works perfectly so I have a problem with spanish codification.

    The mail don t show correctly spanish characters like “ ” neither accents.

    I tested to change the charset into “UTF-8″ but not luck.

    I ll really apreciate so much any solution about this subject.

    Thanks a lot!

    • Jeeremie says:

      21 Jul, 2011

      UTF-8 is for English. Try ISO-8859-1

  47. Dem says:

    24 Jul, 2011

    Very cool script. I m install this script in my site, work without trubles

  48. Pak Youngers says:

    4 Sep, 2011

    I m thank full to you really. It works, nice look easily editable. Thanks. I m using.

    I m looking for to add attachment also.

  49. james says:

    20 Oct, 2011

    Jeeremie, does your script can run fine on windows server too?
    I do have windows server with capability to run php script too that s why i just asked. Any help you can do for me in this regard.

    • Jeeremie says:

      14 Nov, 2011

      As long as you have PHP installed on your server, it should work just fine

  50. SoMoS says:

    27 Oct, 2011

    Please, change the default mail address because tuemail ad gmail.com it s my own address and I receive a lot of messages. Thanks!

    • Jeeremie says:

      14 Nov, 2011

      the email is youremail@domain.com, not tuemail ad gmail.com. I don t know why you received email at all from this scripts. Maybe someone who downloaded this script made a mistake and if so, I am afraid I can t help :(

  51. JASPRIT SINGH says:

    5 Jan, 2012

    sir, iwant to know how to add the relay server in your script.

    it s working fine on all the other hosting but not on the, godaddy hosting could u please help me regarding this.

  52. Sanjeeb Sahu says:

    24 Jan, 2012

    Great stuff. Thanks for sharing and waiting for the next.

  53. Livin'inChina says:

    20 Feb, 2012

    Hi J r mie! I m french too, we are kind of neighbor cuz I live in China! Anyway, congratulations for your blog rich in informations. I ve been trying to use your ContactForm and there is one thing I don t get, it s this : value=””. Can I replace this value by value=”votre nom” for example?
    Thanks in advance.
    Bon courage en Tha lande et merci de partager ton travail comme tu le fais!

  54. says:

    19 May, 2012

    Super work :)

  55. lina says:

    3 Jul, 2012

    MUY BUEN APORTE

  56. drew says:

    17 Aug, 2012

    didn t work for me

  57. Gaby Ferman says:

    21 Sep, 2012

    hi, i loved your contact form… buuuut i m having problems using it on firefox or opera or other browsers. Do you know if i had to add anything to the files?

    • Gaby Ferman says:

      21 Sep, 2012

      sorry, i ve already found the error… i deleted something… thank you anyways for your work on this form!

Leave a Reply

Sorry, comments are closed