0

I am trying to install the Google reCaptcha for a Contact page and I have really limited knowledge with php. I'm unsure as to where the information Google requires should go in my php file. Here are Google's instructions for that:

When your users submit the form where you integrated reCAPTCHA, you'll get as part of the payload a string with the name "g-recaptcha-response". In order to check whether Google has verified that user, send a POST request with these parameters:

URL: https://www.google.com/recaptcha/api/siteverify

secret (required) - xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

response (required) - The value of 'g-recaptcha-response'.

remoteip - The end user's ip address.

And here is my php for the form I use.

<?php
$secret = 'SECRET KEY HERE';
$verificationResponse = $_POST["g-recaptcha-response"];

$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$verificationResponse);
$response = json_decode($response, true);
if($response["success"] === true){
// actions if successful
}else{
// actions if failed
}

/* Set e-mail recipient */
$myemail = "[email protected]";

/* Check all form inputs using check_input function */
$name = check_input($_POST['inputName'], "First and Last");
$email = check_input($_POST['inputEmail'], "Required");
$phone = check_input($_POST['inputPhone']);
$message = check_input($_POST['inputMessage'], "Brief Description");

/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email))
{
show_error("Invalid e-mail address");
}
/* Let's prepare the message for the e-mail */

$subject = "Contact Message from thewiseinvestor.net";

$message = "

Someone has sent you a message using your contact form:

Name: $name
Email: $email
Phone: $phone

Message:
$message

";

/* Send the message using mail() function */
mail($myemail, $subject, $message);

/* Redirect visitor to the thank you page */
header('Location:contact.html');
exit();

/* Functions we used */
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}

function show_error($myError)
{
?>
<html>
<body>

<p>Please correct the following error:</p>
<strong><?php echo $myError; ?></strong>
<p>Hit the back button and try again</p>

</body>
</html>
<?php
exit();
}
?>

HTML Form

<div class="row">
    <div class="col-md-6 message">
    <h2>Send Us A Message</h2>
    <form name="contactform" method="post" action="index.php" class="form-vertical">
      <div class="form-group">
        <label for="inputName" class="control-label">Name</label>
          <input type="text" class="form-control" id="inputName" name="inputName" placeholder="First and Last">
      </div>
      <div class="form-group">
        <label for="inputEmail" class="control-label">Email*</label>
          <input type="text" class="form-control" id="inputEmail" name="inputEmail" placeholder="Required">
      </div>
      <div class="form-group">
        <label for="inputPhone" class="control-label">Phone Number</label>
          <input type="text" class="form-control" id="inputPhone" name="inputPhone" placeholder="Optional">
      </div>
      <div class="form-group">
        <label for="inputMessage" class="control-label">Message</label>
          <textarea class="form-control" rows="5" id="inputMessage" name="inputMessage" placeholder="Brief Description"></textarea>
      </div>
      <div class="g-recaptcha" data-sitekey="DATA SITE KEY HERE"></div>
      <div class="form-group">
        <button type="submit" class="btn btn-custom pull-right hvr-underline-from-left">Send</button>
      </div>
    </form>
    </div> <!-- end col-md-6 --> 

I'm really unsure as to where the above information should go. Any assistance is much appreciated.

2 Answers 2

1

The google reCaptcha mechanism injects a hidden IFrame within your form, and returns a hashed string to your processing script called 'g-recaptcha-response'.

So, in your above PHP script, before /* Set e-mail recipient */ please add the following:

<?php

// error_reporting(E_WARNING);

function readURL($url)
{
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    $output = curl_exec($ch); 
    curl_close($ch); 
    return $output;
}

$secret = "PASTE-YOUR-SECRET-KEY-HERE";
$verificationResponse = $_POST["g-recaptcha-response"];
if( empty($verificationResponse) ) die("Google did not POST the required g-recaptha-response");

$response = readURL("https://www.google.com/recaptcha/api/siteverify?secret=" . $secret . "&response=" . $verificationResponse . "");

$responseArray = json_decode($response, true);
if( $responseArray["success"] !== true) die("Invalid reCaptcha <a href=\"javascript:history.go(-1);\">Try Again</a>");

/* Set e-mail recipient */
$myemail = "[email protected]";

/* Check all form inputs using check_input function */
$name = check_input($_POST['inputName'], "First and Last");
$email = check_input($_POST['inputEmail'], "Required");
$phone = check_input($_POST['inputPhone']);
$message = check_input($_POST['inputMessage'], "Brief Description");

/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email))
{
show_error("Invalid e-mail address");
}
/* Let's prepare the message for the e-mail */

$subject = "Contact Message from thewiseinvestor.net";

$message = "

Someone has sent you a message using your contact form:

Name: $name
Email: $email
Phone: $phone

Message:
$message

";

/* Send the message using mail() function */
mail($myemail, $subject, $message);

/* Redirect visitor to the thank you page */
header('Location:contact.html');
exit();

/* Functions we used */
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}

function show_error($myError)
{
?>
<html>
<body>

<p>Please correct the following error:</p>
<strong><?php echo $myError; ?></strong>
<p>Hit the back button and try again</p>

</body>
</html>
<?php
exit();
}

?>

Should work without any problems. The code will check if the reCaptcha was passed correctly before checking other things or sending you any emails.

Good luck.

Sign up to request clarification or add additional context in comments.

7 Comments

Thank you @Ruslan Abuzant. This is indeed helpful. I am going to add the following where you stated, sorry for another dumb question, the google secret key that is required, where would that go in the above?
No worries, just edited the code snipped and provided a place for you to simply copy-paste your key. It is passed to google verification URL as $secret as you can see.
I'm almost there @Ruslan Abuzant. I updated my php above to reflect the changes you suggested. I also pasted in my html form. I'm getting 3 errors related to line 6 when I hit send. Warning: file_get_contents(): https:// wrapper is disabled in the server configuration by allow_url_fopen=0 in /nfs/c12/h08/mnt/215915/domains/thewiseinvestor.net/html/index.php on line 6
Warning: Cannot modify header information - headers already sent by (output started at /nfs/c12/h08/mnt/215915/domains/thewiseinvestor.net/html/index.php:6) in /nfs/c12/h08/mnt/215915/domains/thewiseinvestor.net/html/index.php on line 49
I am not sure if I am allowed to post a second answer with the complete code, but the errors you are getting are NOT related to the reCaptcha. Your server does NOT have allow_url_fopen enabled in php.ini so you can NOT use file_get_contents, you will need to use CURL instead. As for the second error, it appears because of the first one and will disappear instantly when you manage to read google's response. It means you are sending a header() after sending plain text to your browser which is not allowed. The text being sent here is the first error about file_get_contents.
|
0

There is official documentation for reCaptcha and ready to use PHP lib.

Here you find ready to use code and comments: https://github.com/google/recaptcha

Your server-side code will look like this:

<?php
$recaptcha = new \ReCaptcha\ReCaptcha($secret);
$resp = $recaptcha->verify($gRecaptchaResponse, $remoteIp);
if ($resp->isSuccess()) {
    // verified!
} else {
    $errors = $resp->getErrorCodes();
}

1 Comment

The user has stated that they have a limited knowledge with php. I doubt introducing namespace classes and third party libraries will be of any help. Still, your answer is useful of course, thank you. ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.