phphtmlrecaptchamail-form

Can someone help me to set up reCAPTCHA server side?


I'm new to PHP and i am trying to add reCaptcha in a PHP mail form.
The code is similar to this:

PHP:

<?php if (isset($_POST['send'])) {
    $to = "mymail@gmail.com";
    $subject = "subject";
    $message = 'Name: ' . $_POST['name'] . "\n";
    $message .= 'Email: ' . $_POST['email'] . "\n";
    $message .= 'IP: ' . $_SERVER['REMOTE_ADDR'] . "\n";
    $message .= 'Message: ' . $_POST['message'];
    $success = mail($to, $subject, $message); }?>`

HTML:

<form method="post">
<p>name</p>
<input type="text" name="name" class="contactformimput"/>
<p>email*</p>
<input type="text" name="email" class="contactformimput"/>
<p>number</p>
<input type="text" name="number" class="contactformimput"/>
<p>Messaggio*</p>
<input type="text" name="message" onkeyup="adjust_textarea(this)" class="contactformimput" id="contactformtext">
<div class="g-recaptcha" data-sitekey="__MYPUBBLICKEY__"></div>
<div id="divcontactbutton">
<input type="reset" name="send" value="Resetta" class="button" id="resetmessage"/>
<input type="submit" name="send" value="Invia Messaggio" class="button" id="sendmessage"/>
</div>
</form>

Solution

  • use Google's recaptcha easy to use, very first thing you need to do is register your website on Google recaptcha to do that GoogleRECAPTCHA

    Once submit, Google will provide you following two information.

    Integrate it in your site inside head tag use this code

    <script src='https://www.google.com/recaptcha/api.js'></script>
    

    To show the widget in your form use this code in your form

    <div class="g-recaptcha" data-sitekey="SITE-KEY"></div>
    

    When the form gets submitted to Server, this script will send g-recaptcha-response as a POST data. You will need to verify it in order to see whether user has checked the Captcha or not

    Php code for checking

     if(isset($_POST['g-recaptcha-response'])){
          $captcha=$_POST['g-recaptcha-response'];
        }
        if(!$captcha){
          echo '<h2>Check captcha .</h2>';
          exit;
        }
        $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=YOUR SECRET KEY&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
        if($response.success==false)
        {
            //redirect back
        }else
        {
           //your mail code 
        }