Skip to content

Instantly share code, notes, and snippets.

@josephilipraja
Last active February 7, 2021 14:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save josephilipraja/3ec08844e9b3ec5acb9f044e3c4ec387 to your computer and use it in GitHub Desktop.
Save josephilipraja/3ec08844e9b3ec5acb9f044e3c4ec387 to your computer and use it in GitHub Desktop.
Simple PHP Server-side verification of Google re-Captcha.
<?php
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])):
// Your site secret key obtained from Google
$secret = '#####################################';
$grResponse = $_POST['g-recaptcha-response'];
// Verify with Google Servers
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$grResponse);
$responseData = json_decode($verifyResponse);
if($responseData->success):
// VERIFICATION SUCCESS
else:
// VERIFICATION FAILED
endif;
else:
// INVALID REQUEST
endif;
?>
@omimouni
Copy link

This may cause some problem in the HTTPS I use this one and I think it's better

<?php
$params = [
		'secret' 	=> 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
		'response' 	=> $_POST['g-recaptcha-response']
	];
	$opts = [
		'http' => [
			'method' 	=> 'POST',
			'header' 	=> 'Content-type: application/x-www-form-urlencoded',
			'content' 	=> http_build_query($params)
		]
	];
	$context 	= stream_context_create($opts);
	$res 		= file_get_contents('https://www.google.com/recaptcha/api/siteverify',false,$context);
	$res 		= json_decode($res,true);

        if($res['success']) :
		// Code block if verified
	else :
		// code block if not
	endif;

?>

@Jeffsprojects
Copy link

Hey Kraphty there are errors in the code. This script doesn't work on my page

@Jeffsprojects
Copy link

none of this code works correctly & if you use it you will not be able to submit the form. Even the rived code is not working correctly.

@JboyJW
Copy link

JboyJW commented Sep 7, 2018

Works for me! I used Kraphty's code and it does what it should. Be sure to update the secret to be the correct secret for your account.

@kamleshwebtech
Copy link

Thanks @Kraphty Your code is working like charm. BTW how to validate recaptcha on client side? I mean to say how can i restrict user to click on recaptcha icon otherwise he can not submit the form. Kindly suggest me. Thank a lot 👍

@kamleshwebtech
Copy link

kamleshwebtech commented Jan 19, 2019

<title>Check Re-captcha</title> <style> .form-wrapper-outer{ padding: 40px; border-radius: 8px; margin: auto; width: 460px; border: 1px solid #DADCE0; margin-top: 7%; }
    .field-wrapper{
        position: relative;
        margin-bottom: 15px;
    }
    
    .field-wrapper input{
        border: 1px solid #DADCE0;
        padding: 15px;
        border-radius: 4px;
        width: 100%;
    }

    .field-wrapper input:focus{
        border:1px solid #1A73E8;
    }

    .field-wrapper .field-placeholder{
        font-size: 16px;
        position: absolute;
        /* background: #fff; */
        bottom: 17px;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
        color: #80868b;
        left: 8px;
        padding: 0 8px;
        -webkit-transition: transform 150ms cubic-bezier(0.4,0,0.2,1),opacity 150ms cubic-bezier(0.4,0,0.2,1);
        transition: transform 150ms cubic-bezier(0.4,0,0.2,1),opacity 150ms cubic-bezier(0.4,0,0.2,1);
        z-index: 1;

        text-align: left;
        width: 100%;
    }        
    
    .field-wrapper .field-placeholder span{
        background: #ffffff;
        padding: 0px 8px;
    }

    .field-wrapper input:not([disabled]):focus~.field-placeholder
    {
        color:#1A73E8;
    }
    .field-wrapper input:not([disabled]):focus~.field-placeholder,
    .field-wrapper.hasValue input:not([disabled])~.field-placeholder
    {
        -webkit-transform: scale(.75) translateY(-39px) translateX(-60px);
        transform: scale(.75) translateY(-39px) translateX(-60px);
        
    }


    .field-wrapper.field-error{
      border: 1px solid red;
    }
    .field-wrapper.field-error .field-placeholder span{
      color: red;
    }

    #message-wrap {
        padding: 15px;
        text-align: center;
        display: none;
        border-radius: 4px;
    }

    #message-wrap.success-msg{
      color:green;
      background: #e3ffd5;
    }
    #message-wrap.error-msg{
      color:red;
      background: #ffd5d5;
    }
</style>
	<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

	<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer>
</script>
	  	<div class="form-wrapper-outer">

		    <form action="#" method="POST" name="htmlform" id="test-form" novalidate>
		      <div class="field-wrapper">
		        <div id="message-wrap">
		          <span></span>
		        </div>
		      </div>
		      <div class="field-wrapper">
		        <input type="email" name="email" class="form-checkfield" id="" required>
		        <div class="field-placeholder"><span>Enter your email</span></div>
		      </div>
		      <div class="field-wrapper">
		        <input type="text" name="name" class="form-checkfield" id="" required>
		        <div class="field-placeholder"><span>Enter your name</span></div>
		      </div>
		      <div class="field-wrapper">
		        <input type="text" name="phone" class="form-checkfield" id="" required>
		        <div class="field-placeholder"><span>Enter your phone</span></div>
		      </div>
		      <div class="field-wrapper">
		        <div id="google_recaptcha"></div>
		      </div>
		      <div class="field-wrapper">
		        <input type="button" id="submit-test-form" value="Submit">
		      </div>
		    </form>

		  </div>


		<script>
			
			    var onloadCallback = function() {
			        grecaptcha.render('google_recaptcha', {
			          'sitekey' : '6Le3A4sUAXXXXXXXXXXXXXXXXXXbHuaqTWk0-'
			        });
			      };
			      
			      $(function () {
			        //Check if required fields are filled
			        function checkifreqfld() {
			                var isFormFilled = true;
			                $("#test-form").find(".form-checkfield:visible").each(function () {
			                    var value = $.trim($(this).val());
			                    if ($(this).prop('required')) {
			                        if (value.length < 1) {
			                          $(this).closest(".field-wrapper").addClass("field-error");
			                          isFormFilled = false;
			                        } else {
			                          $(this).closest(".field-wrapper").removeClass("field-error");
			                        }
			                    } else {
			                        $(this).closest(".field-wrapper").removeClass("field-error");
			                    }
			                });
			                return isFormFilled;
			          }

			        //Form Submit Event
			        $("#submit-test-form").click(function () {
			            if (checkifreqfld()) {
			              event.preventDefault();
			              var rcres = grecaptcha.getResponse();
			              if(rcres.length){
			                grecaptcha.reset();
			                showHideMsg("Form Submitted!","success");
			              }else{
			                showHideMsg("Please verify reCAPTCHA","error");
			              }
			            } else {
			                showHideMsg("Fill required fields!","error");
			            }
			        });

			        //Show/Hide Message
			        function showHideMsg(message,type){
			          if(type == "success"){
			            $("#message-wrap").addClass("success-msg").removeClass("error-msg");
			          }else if(type == "error"){
			            $("#message-wrap").removeClass("success-msg").addClass("error-msg");
			          }

			          $("#message-wrap").stop()
			          .slideDown()
			          .html(message)
			          .delay(1500)
			          .slideUp();
			        }


			        //Google Style InputFields
			        $(".field-wrapper .field-placeholder").on("click", function () {
			          $(this).closest(".field-wrapper").find("input").focus();
			        });
			        $(".field-wrapper input").on("keyup", function () {
			          var value = $.trim($(this).val());
			            if (value) {
			              $(this).closest(".field-wrapper").addClass("hasValue");
			            } else {
			              $(this).closest(".field-wrapper").removeClass("hasValue");
			            }
			        });
			      });

		</script>

</body>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment