simple recaptcha php code example

Example 1: how to add recaptcha validation in php

index.html

<html>
  <head>
    <title>Google recapcha demo - Codeforgeek</title>
    <script src='https://www.google.com/recaptcha/api.js'></script>
  </head>
  <body>
    <h1>Google reCAPTHA Demo</h1>
    <form id="comment_form" action="form.php" method="post">
      <input type="email" placeholder="Type your email" size="40"><br><br>
      <textarea name="comment" rows="8" cols="39"></textarea><br><br>
      <input type="submit" name="submit" value="Post comment"><br><br>
      <div class="g-recaptcha" data-sitekey="=== Your site key ==="></div>
    </form>
  </body>
</html>
verify.php

<?php
    $email; $comment; $captcha;

    if(isset($_POST['email']))
        $email=$_POST['email'];
    if(isset($_POST['comment']))
        $comment=$_POST['comment'];
    if(isset($_POST['g-recaptcha-response']))
        $captcha=$_POST['g-recaptcha-response'];

    if(!$captcha){
        echo '<h2>Please check the the captcha form.</h2>';
        exit;
    }

    $response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=YOUR SECRET KEY&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']), true);
    if($response['success'] == false)
    {
        echo '<h2>You are spammer ! Get the @$%K out</h2>';
    }
    else
    {
        echo '<h2>Thanks for posting comment.</h2>';
    }
?>

Example 2: contact form php with captcha

<form id="frmContact" action="" method="POST" novalidate="novalidate">
    <div class="label">Name:</div>
    <div class="field">
        <input type="text" id="name" name="name"
            placeholder="enter your name here"
            title="Please enter your name" class="required"
            aria-required="true" required>
    </div>
    <div class="label">Email:</div>
    <div class="field">
        <input type="text" id="email" name="email"
            placeholder="enter your email address here"
            title="Please enter your email address"
            class="required email" aria-required="true" required>
    </div>
    <div class="label">Phone Number:</div>
    <div class="field">
        <input type="text" id="phone" name="phone"
            placeholder="enter your phone number here"
            title="Please enter your phone number"
            class="required phone" aria-required="true" required>
    </div>
    <div class="label">Comments:</div>
    <div class="field">
        <textarea id="comment-content" name="content"
            placeholder="enter your comments here"></textarea>
    </div>
    <div class="g-recaptcha" data-sitekey="<?php echo SITE_KEY; ?>"></div>
    <div id="mail-status"></div>
    <button type="Submit" id="send-message" style="clear: both;">Send
        Message</button>
</form>

Tags:

Php Example