Add Google reCAPTCHA to your PHP site

How it works

See steps below

  1. If you are on Ubuntu, install php-curl
  2. Register for a key and secret -> https://www.google.com/recaptcha/admin/create
  3. Load js with client key -> src=”https://www.google.com/recaptcha/api.js?render=CLIENT_KEY”
  4. Add following javascript to you client side html code
    • $(‘#contact’).submit(function(event) {
    • event.preventDefault();
    • grecaptcha.ready(function() {
    • grecaptcha.execute(‘CLIENT_KEY’, {action: ‘submit’}).then(function(token) {
    • $(‘#contact’).prepend(”);
    • $(‘#contact’).prepend(”);
    • $(‘#contact’).unbind(‘submit’).submit();
    • });
    • });
    • });
  5. Add following to server
    • define(“RECAPTCHA_V3_SECRET_KEY”, ‘YOUR_SECRET’);
    • /*
    • if (isset($_POST[’email’]) && $_POST[’email’]) {
    • $email = filter_var($_POST[’email’], FILTER_SANITIZE_STRING);
    • } else {
    • // set error message and redirect back to form…
    • header(‘location: index.php’);
    • exit;
    • }
    • */
    • $token = $_POST[‘token’];
    • $action = $_POST[‘action’];
    • // call curl to POST request
    • $ch = curl_init();
    • curl_setopt($ch, CURLOPT_URL,”https://www.google.com/recaptcha/api/siteverify”);
    • curl_setopt($ch, CURLOPT_POST, 1);
    • curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array(‘secret’ => RECAPTCHA_V3_SECRET_KEY, ‘response’ => $token)));
    • curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    • $response = curl_exec($ch);
    • curl_close($ch);
    • $arrResponse = json_decode($response, true);
    • if($arrResponse[“success”] == ‘1’ && $arrResponse[“score”] >= 0.5) {
    • //success
    • }
    • else{
    • //error
    • }

Advertisement

About buminda

buminda.com
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s