[contact-form-7 id="24084" title="Feedback ES"]

Plantillas Destacadas

¿Cómo crear un formulario de contacto en HTML?

Este tutorial contiene instrucciones para crear un formulario de contacto muy sencillo para plantillas basadas en HTML.

En primer lugar hay que crear dos ficheros: contact_form.html y contact.php. El primer fichero contendrá el código HTML para el formulario y el segundo fichero procesará los datos del formulario.

HTML

Vamos a revisar el código HTML del formulario de contacto:

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

Y así es como se aparecerá en el navegador web

HTML contact form

Vamos a examinar algunos de los aspectos principales. La etiqueta <form> debe tener 2 atributos adicionales:

action=”contact.php” – este atributo especifica la dirección que va a recibir los datos enviados de los campos del formulario de contacto

method=”post” – este atributo especifica la manera del envio de los datos del formulario al fichero especificado en el atributo action

Las etiquetas <input> y <textarea> deben tener un atributo “name” con un identificador único. Este atributo es utilizado para identificar los datos del formulario después del envio al servidor.
Y entre dos elementos entrados que se utilizan como botones Enviar y Borrar, uno debe tener type=”submit” asignado y otro – type=”reset”

Y eso es todo. Mutyfácil.

PHP

Ahora vamos a trabajar con el fichero contact.php que realmente recogerá los datos de los campos, creará un mensaje y enviarálo a su dirección de correo electrónico. Puede descargar el fichero contact.php. En este tutorial vamos a revisar el código del fichero con los comentarios a las secciones más importantes.

Asignar los datos enviados desde los campos del formulario de contacto (cf_name, cf_email, cf_message) a los variables php ($cf_message, $field_email, $field_message)

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

$mail_to contendrá la dirección de correo electrónico del propietario del sitio. Se puede especificar varios correos electrónicos, separándolos con comas (por ejemplo, [email protected], [email protected])

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

Tema/Asunto del mensaje de correo electrónico que recibe

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

Organizar el mensaje

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

Crear las cabeceras del mensaje

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

Definir la función mail() y asignarla al variable $mail_status, que se utiliza para comprobar si el mensaje de correo ha sido enviado o no.

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

Si la fucnión mail() se ejecuta con éxito, entonces utilice el código:

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
}

Si la fucnión mail() no trabaja, entonces utilice el código:

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
}?>

También Usted puede descargar los ficheros compilados compiled contact_form.html y contact.php en el paquete

 

Por favor, revise el tutorial ¿cómo agregar campos al formulario de contacto?

¿Cómo crear un formulario de contacto en HTML?, 3.8 out of 5 based on 14 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

  • 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)?

  • 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

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

  • 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

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

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

  • 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?

    • Anónimo

      1. To make the messages be setnt to your specific email address edit the $mail_to = ‘[email protected]’; variable. Replace [email protected] with your email address

      2. Unfortunately this can’t be done in this example. To change the window style you need to create the JavaScript based form.

  • Anónimo

    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”

  • Anónimo

    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.

  • 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!

  • 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

  • nice, perfect!

  • Adetola Sadiku

    Here is my error precisely ” Warning mail() [function.mail]: SMTP server response 550 5.7.1 Unable to relay for [email protected] etc….. contact.php on line 16

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

  • Fantastic. Thank you!

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

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

    • service2u

      it goes in the same dir as the contact HTML,

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

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

      • 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

    when i am using the contact form code when i press submit button on server side .php coding is displaying and even i cannot receive any following mail which specified in the contact.php.pls answer to the post to my mail [email protected]

    • 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 = ‘[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!

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

  • Afsal mohammed

    thank you from adskart.

  • Chantal M. Bourgonje

    Very grateful for this information. It works! It even worked at my first try. And it was simple too. Thank you so much for this.

  • Thanks. Very helpful. :-D

  • sturzi

    Thank you very much. This is exactly the kind of explanation I sought.

  • vivek singh

    thanks a lot for the code

  • Alexandru Tudoran

    Muchas gracias, nos ha ayudado con la landing page de nuestra empresa

  • Daniel Alejandro Sánchez Norie

    Excelente y super sencillo, lo aplique a un diseño diferente de un template específico y funcionó de maravilla, ya hasta me siento un web mater. jeje Gracias Monsters

  • vinayak jambhale

    thank you soooo muchhh sir…..
    that was really helpful for beginners….
    it works greatly..