This site uses cookies. Read privacy policy. Click exit to agree×

PHP contact form script with reCaptcha

Baner

For all of you who don’t like using contact form plugins I have made available a php script I have been using throughout my projects. The package includes PHP as well as CSS and JS files. The code is commented so that you won’t get lost.

Input fields are validated and remember the text after the page reloads (e.g. when the form hasn’t been filled in correctly). ReCaptcha along with a special “blind” field prevent spam attacks. The HTML is 100% valid and displays correctly in all fairly modern browsers. Due to the addition of reCaptcha JS needs to be enabled on the users’ browsers.

Before you insert it on your site you will have to get reCaptcha private and public keys. Enjoy

  • paul

    thanks for your help on reCaptcha. i need advise on one style that needs to be tweeked to work properly that i can’t figure out. when entering the input field, the text and background does not fade to white. so the text i input types right over the label. here is the sample http://72pixels.com/connect2.php

  • http://troncorp.co.za Reynardt

    Thank you for this tutorial. I’m having a problem though, when I submit the form I get an error: “Could not open Socket”

    Any idea? Thanks.

    • ChrisPlaneta

      No idea. I’ve never had this problem nor heard about anybody having it. The bast thing would be to ask a question on stackoverflow. They should help you out.

  • http://www.worlds-best-watches.com Adam

    Thanks for the download. Was using an old random generated math captcha but has recently been hit by the bots daily. It was the only one I had that hadn’t been cracked on my sites yet. Now I will be moving them all across to your script! Perfect soulution….

    • ChrisPlaneta

      Sure thing. Glad I could help:)

  • http://www.agilewebsitedev.com/ Pali Madra

    The demo form can be sent even if you provide the wrong captcha! There is an error somewhere.

  • ChrisPlaneta

    Hi Pali,

    Thank you for the info. I’ve checked it out but it worked for me. Did you provide a totally wrong answer to the captcha or made just a small mistake?

    I’m asking this because if it’s the latter than everything is fine. The thing with recaptcha is that there are 2 words provided by the system. One of them (but not necessarily the first one) is the real test. The other one is a word that book readers had problems understanding (Google uses recaptcha as a book-digitisation tool). It means that the system doesn’t have a clue what this word is. If you provide answer that is similar but not exactly what it really says than the test will be passed. Now you might be asking yourself “Wouldn’t it also work if I typed something totally different?”. Weeeelll. Not really.

    The thing is that the same word is also sent to a few dozen other people. If majority of them thinks that this word means ABC and you provide answer XYZ than it won’t be passed. If, on the other hand, your answer is ABD than this test word is barely (but still) passed.

    Best,
    Chris

  • http://www.agilewebsitedev.com/ Pali Madra

    Hey Chris,

    I must appreciate your prompt response.

    Actually what I made was a small change. I was asked to input “The holoore” and I did input “Th holoore” and the form was submitted.

    The good news is that I tried before that and the form did return a captcha error. I was asked to fill in “the toryaxe” and I filled in “the toryax” and the error was promptly displaced which was pleasing.

    Thank you for explaining how Recaptcha works. I knew that but it slipped out of my mind that it could be cause of the issue. You are absolutely right that given the logic there would be some ‘false positives’ if I might say so.

    Thank you for the response once again and you have a great website in terms of design and content as well.

  • http://www.byronbaybeauty.com Sam

    Hi Chris,

    Great script! Thanks! Have installed but when I refresh the site I get a ‘Input error: k: Format of site key was invalid’. I have recreated the recaptcha keys twice but still the same result. Can you offer any suggestions as to why this might be happening?

    Cheers,

    Sam

    • http://chrisplaneta.com ChrisPlaneta

      That’s the first time I’ve heard about such error. After a bit of googling I’ve found this

    • http://www.byronbaybeauty.com Sam

      Thanks, Chris. Its my fault, I tried to install the script in a hurry and missed putting the public key in toward the bottom of the file. Sorry! Thanks for the prompt response though. All working perfect now!!

  • srk90

    thank you very much chris.
    had been searching for the correct code since a while and here it is.
    as i have just stRated web dev,this was really helpful.
    i would really appreciate if you could tell me the code if i want
    to add another field containing the contact number *required would be grateful to you.

    THANK YOU.

    • ChrisPlaneta

      Hi there,
      To add a new field you just have to copy lines 36-43, paste it again after these lines and change wording – wherever you have a word with “author” in it you need to change it to your word e.g. “tel” or “number”. Next, go to line 77 and add “\n\n$formYourWord” before semicolon. To add a field to the form you need to copy lines 125 – 130 and also change the wording as I’ve said. This way you can add any number of fields.
      Pay attention to capitals though. Variables names hae to match.

      Best regards,
      Chris

  • Jens

    Hi,

    thanks a lot for your contact form script. It was easy to implement it and change css, but when I press “send message” I got the following error message:

    “Fatal error: Call to undefined function: filter_var() in /hom/form/index.php on line 37″

    Do you have an idea what goes wrong?
    Thanks!

    • Jens

      Hi again,

      I tested it on another webspace and it works.
      Can you please let me know which PHP Version is needed?

      Is the skript free to use it on commercial websites?

      Thanks!

    • Chris Planeta

      Hi Jens,

      Filter_var works from PHP5 up. Good for pointing this out because, to tell you the truth, I had no idea what the problem was. This one seems the most likely.

      You can you the script wherever you want:)

  • rufuz

    Hi there,
    I’m having a problem which probably is not directly related to your (great) script but maybe you can help me and anyone who wants to do something similar.
    I have:
    $varmail = $_POST['varmail'];

    which I submit and pass from another page with an hidden field.

    it echoes, print_r or dumps correctly as “myemail@domain.com” BUT when I put:

    $email = $varmail;
    or
    $email = $_POST['varmail'];
    or
    mail($_POST['varmail'], $subject, $body, $headers);

    the script doesn’t send the email.
    Note that the email is correctly sent when I declare e.g. $varmail=”myemail@domain.com”

    Can you help?

    thank you very much!

    • ChrisPlaneta

      As i see it your $varmail value gets lost on page refresh. You need to have it existing physically in output html.

      1. Save the $varmail in a hidden field so that it shows in html.
      2. Next, go to line 48 – add another if before the one that’s already there. You should have if(hiddenvalueexists){$formEmail = $hiddenvalue}else if(!filter…){}else()

      Should be fine:) If not then I don’t know:/

  • rufuz

    thank you very much! this solved:
    <input type="hidden" value="” name=”pvarmail”>

    $spvarmail = (filter_var($_POST['pvarmail'], FILTER_SANITIZE_EMAIL));

    and finally

    $emailTo = $spvarmail;

    maybe not elegant, but it works now (hope it’s not insecure)!

    thanks again!

    • rufuz

      oops value of hidden field has been stripped… it was the echo of $_POST['varmail']

      :)

  • Glenn

    Thanks for the script! A question for you… how would I go about adding a select menu to the form?

  • Kris

    hey!
    I got letters like ąźćńółęśż. does this script write it in email properly? i dont know download this or not?

    • ChrisPlaneta

      Sure it does:) It should handle even chinese as long as the script files are saved in utf-8 (and they are):)

  • Kris

    At last! I got similar script gives me strange “letters” if somebody write letters like ąćźś:) Thanks man:)

  • Kris

    Hey again. Script doesnt work with my ąćńł etc… i typed:
    jążźćńółęś i co?
    i saw in mail:
    jążźćńółęś i co?
    maybe additional headers defining that message is utf8?

  • Kris

    if im using horde, thunderbird or no matter what – i see what i wrote:(

    • Chris Planeta

      Can’t be. I’m using it in other projects (multilingual as well) and it works flawlessly. There must be sth wrong on your side. I can’t help you with it though.

  • Kris

    You see it. Doesnt match.
    I copied/pasted/changed keys and email and You see what i see.
    Do You see these strange characters? As You can see script doesnt work anywhere (with polish language) but ive searched google and found:
    $header = “MIME-Version: 1.0\r\n”;
    $header .=”Content-type: text/html; charset=UTF-8\r\n”;
    $header .= “Content-Transfer-Encoding: 8bit\n”;
    $header .=”From: \r\n”;
    i tried to paste it but with no effect (maybe i dont know where or how).

  • Kris

    Or ill send You some text with national letters and Youll mail it to see if its my fault or not?

  • http://www.jwcc.com.au J W Capital Corporation

    Hi Chris, been using this for a while now but finding I’m getting hammered with spam. Around 20-30 per day. Seems someone has targeted this form, is there anything I can do? Note, phone numbers entered always seem to be 123456… Ideas? thoughts? Thanks, Adam

    • Chris Planeta

      That’s really odd. Are you sure that the spam is sent via the form? Maybe somebody’s sending you the mail directly? If yes, have you installed the form correctly and tested the recaptcha before going live?

  • http://www.lukasgraphics.com Matt Lokay

    I can’t thank you enough for this code. It saved my day and was exactly what I was searching for.

    My editted form can be seen here:

    http://www.sipesandson.com/enquiries_concept4.php

    As you can see, I wiped out the $subject code and added $phone number. This causes an issue where now there is no subject line listed in the received email.

    1. How do I code it so the email you receive says something like this without an actual subject field?

    ‘Sipes and Son Enquiry from: ‘ . $formAuthor . ‘ | ‘

    2. Also how do I have the form be sent to more than one email address?

    • Chris Planeta

      To send the message to many receipients you just add one more email to $emailTo (after a coma).

      If you want to delete the subject field:
      1. delete the code from the form (obviously)
      2. delete the section of php that validates the subject line
      3. change $subject = … to $subject = ‘Sipes and Son Enquiry from: ‘ . $formAuthor;

      That’s it:)

    • matt

      Works. Thanks a ton!

  • http://bostonburger.net Rick

    Are you still supporting this form? Just want to say it looks awesome. I can’t get it to work correctly though. If you go to the site you will know what I mean.

    • http://chrisplaneta.com Chris Planeta

      It’s in PHP 5 so until PHP 6 is introduced or some parts of its code get deprecated the aboe code will work. I can’t see the form in use on your site though so I cannot tell you what’s wrong with it. Double check everything. It will work.

  • will

    great form – it is saving my life!! I have it working and I am editing it with success but I was wondering how I can add a form field that isn’t required using the coding structure you have here? I can make them all required but it would be nice and very appreciated.

  • http://playwrightsofnewyork.org Marc

    Hi – thanks so much for the form code. Saved my skin as my php skills are very minimal. I put it into a site I maintain last December and it successfully stopped spam, but now it’s starting again and I haven’t touched the files since then.

    Any thoughts would be greatly appreciated!

    Here’s the page:
    playwrightsofnewyork.org/contact.html

    Thanks so much!

    • http://ebizneskrokpokroku.pl Chris Planeta

      Not really. It’s odd that somebdy’s getting through captcha. Don’t you display the address anywhere on the site?

  • http://none Ursula

    I downloaded the demo and trying it “as is” and I get the following error:

    Notice: Undefined variable: captchaErrorMsg in index.php on line 105

    I dont see that variable defined anywhere. what am I doing wrong?

    • http://ebizneskrokpokroku.pl Chris Planeta

      You need to register your site on captcha site (link in article), download two keys that they will give you and enter them in the code in places that I pointed.

      Then you just upload everything to your web serwer and voilea:)

  • http://www.buyandsavebig.com Leslie Cox

    Hi Chris, I’m a total novice when it comes to forms, but I have worked on many websites before over the years, and then stopped, so I’m a little behind on my php. I cant figure out where to put the form page, Is it index.php? do I put that on my website with a changed name like form.php or do I make another php page and copy your form coding, or how does the form appear on my page I’m making? I’m totally stumped. I can see how to fill in all the necessary php pages and recaptcha, but I’m not sure how to get the form on my web site. Any help would be most welcome.
    Best regards,
    Leslie.

    • http://ebizneskrokpokroku.pl Chris Planeta

      Hi Leslie,

      You should copy the code and paste it inside the php template of the page you want to display it on. In other words, you should go to your site’s files on the web server (e.g. with FileZilla), find theme folder, find template where you want the form to display (e.g. page-contact.php) and paste it there.

  • http://www.aculei.net/~eredien/ Cassandra

    Hi Chris. This was exactly what I was looking for in a PHP/ReCaptcha form and thanks for providing it. I look forward to tweaking the css a little more for my site. However, I am getting a problem: when I type on your form demo the label text fades away and you get a nice clean entry, but when I type on my form the label text does not fade away and the input writes over the label text, making it hard to read and messy. So far nothing else seems to be the matter. Would you mind taking a look? http://www.aculei.net/~eredien/contact.php

  • http://www.aculei.net/~eredien/ Cassandra

    When I made the text label area background white in the CSS, the text label fields disappeared. I’ve defined the font in the CSS body as #000 but it’s still not showing up after I put the new file.

    • http://chrisplaneta.com Chris Planeta

      Hi there. The solution is easy. Just add the javascript file that was in the download file (or add its content to your existing js files in order not to multiply them). It’s responsible for handling label text animations.

  • Trip

    Can you send to multiple email accounts from the form?

    • http://ebizneskrokpokroku.pl Chris Planeta

      Yup:) Simply add more addresses in the appropriate place in the code. You should be able to find it easily

  • http://www.epubsearch.com/ EPUB

    This saved a lot of my time. Thank you very much!

  • Glen

    Hi,

    Thanks for this script, I use it on all my websites! Can I ask though, how would I implement a dropdown list option and a checkbox option into it?

    Cheers,

    Glen

    • http://ebizneskrokpokroku.pl Chris Planeta

      Hi there,

      Sorry but the functions that you need would require me to write half of the script from fresh. I don’t add new things to it any longer.

  • http://www.mycorvette.co.uk Paul

    hi Chris
    irealise this is an old post and you may not be supporting it anymore but if you are, any chance you could have a quick look at my site and let me know where I have gone wrong. Im a complete n00b to websites and use a wysiwyg editor so am unsure of coding.
    On my contact page, everything seems to work but 2 things…it looks messy and I never get an email from the enquiry. Would appreciate any help or advice.
    Thanks.

    • http://ebizneskrokpokroku.pl/ Chris Planeta

      Hi Paul,
      The form looks messy because it’s not styled in your CSS code. That’s why it looks this way. As for sending, did you enter your email address in the script of the form? If yes, did you enter both the ReCaptcha keys correctly? If you did both these things you may also try to enter the address of the contact form in this piece of code >> <form action="put the address of the contact page here">

  • http://www.mycorvette.co.uk Paul

    Hi Chris,
    Thanks for the prompt reply. Ive been away with work but just added the code so now form looks correct and it appears to be sending the mails.
    Only problem now ( something I must have messed up ) is that the original wording stays in the form when you type in Name, email etc. It just overlays the text instead of the original text disappearing when you click in the box. Any ideas what i have done? Sorry to be a pain.
    Regards,
    Paul

  • http://www.mycorvette.co.uk Paul

    There was an error uploading the js folder. All working now I think.
    Many thanks for the form and the help, truly appreciated.

    • http://chrisplaneta.com Chris Planeta

      I’m glad to know the problem is solved:)

  • http://josh-graham.com/contact.php Josh

    Hi Chris,

    Having a similar problem to Paul. I cannot get the form to send an email. The form shows errors if you do not fill in boxes correctly and displays thank you text if done correctly but I do not receive an email. I have checked both of my keys are correct, my email address is entered correctly and I have added the . Any ideas as to why I’m not receiving anything?

    Thanks

    Josh

    • Chris Planeta

      Well, not really. Could you paste here the line of code where you entered your email? To do it you need to change its coding first by using e.g. http://www.elliotswan.com/postable/ Otherwise WordPress won’t show the code.

  • http://josh-graham.com Josh

    Hi Chris,

    This is the code I used:

    if (($resp->is_valid) && (!isset($hasError))) {
    $emailTo = 'contact@josh-graham.com'; // here you must enter the email address you want the email sent to

    And the file is hosted here if it helps:

    https://www.dropbox.com/s/2iz9p22p9htyr2r/contact.php

    Appreciate the help,

    Josh

    • http://ebizneskrokpokroku.pl Chris Planeta

      Hi Josh,

      Try putting in form > action the exact url of the page with the contact form (with http and all). If it won’t help that the only reason I can think of is that the PHP version on your server is too old. In one of the previous comments somebody noted that the script doesn’t work on PHP4.

  • Josh

    Hi Chris,

    Thanks for the suggestions and taking the time to look over my code. I had previously tried it with the full URL and don’t think it helped. I’ll have another go though. The server is running PHP 5.4 to the best of my knowledge so that should be okay. Very strange that it doesn’t seem to want to work, perhaps my host is the issue (GoDaddy), I’ll contact them if nothing else works.

    Thanks

    Josh

  • Josh

    Hey Chris,

    Sorry to double post. Very strange occurrence but today I randomly received a load of emails to the email account on the form that I sent days ago. I sent a test message through the form earlier this afternoon and it seems to have taken a few hours to come through. So I have no idea what’s causing the seemingly random delay but the form SEEMS to be working.

    • http://ebizneskrokpokroku.pl Chris Planeta

      Wow. It’s the first time I’ve heard anything like that. Very odd indeed.

  • http://www.solutionzplanet.com umar

    Hi Chris,
    I am facing the issue and found no help. I will be really thankful to you if you help me in this matter. I am using recaptcha with easy contact form. But recaptcha is not working as I entered all right words but it always says captcha is wrong. I know the issue is not related to your code or issue. But Please help me.
    website address is http://www.solutionzplanet.com/contact-us

    Thanks,
    Umar

  • Anna

    Hi, love the contact form. I am trying to build on it and fill out its functionality.

    I’ve opted to do away with the interior labels and add my own to the exterior, kind of seems like going backwards but I just sort of want it this way :)

    I have stuff like this that works just fine:

    .author-red-error {color: blue;}

    I am trying to unify your Recaptcha valid + singular condition to send the email with my Recaptcha valid + multiple condition to send an email. Help! lol

    _FROM_
    if (($resp->is_valid) && (!isset($hasError))) {

    _TO_
    if (($resp->is_valid) && (!isset($authorhasError) && (!isset($emailhasError) && (!isset($messagehasError))) {

    Thanks x

  • Anna

    Pastie of complete thing is here:

    http://pastie.org/private/4kk4vjbdfat7k4xzoruhyg