구글 reCaptcha 를 php 로 연동하기 하기 위해서는 먼저 'Site key' 와 'Secret key' 를 발급받아야 합니다. 연동하고자 하는 도메인 주소나 localhost 를 입력하면 바로 발급받을 수 있으니 어렵지는 않습니다.

먼저 아래 주소로 접속해 주세요.

https://www.google.com/recaptcha/intro/index.html

다음에는 도메인 주소를 입력하고 등록을 클릭합니다.


등록 즉시 'Site key' 'Secret key' 를 발급받아 주세요. 'Site key', 'Secret key' 값을 아래 소스 값에 기입 후 바로 사용하면 되겠습니다.

<?php
 $sitekey = 'Site Key'; 
 $secretKey = "Secret Key"; 

 if($_SERVER['REQUEST_METHOD'] === "POST") {
     $name = null;
     $contents = null;
     $recaptcha = null;
     if($_POST['name']){
         $name = $_POST['name'];
     }
     if($_POST['contents']){
         $contents = $_POST['contents'];
     }
     if($_POST['g-recaptcha-response']){
         $recaptcha = $_POST['g-recaptcha-response'];     
     }
     if($recaptcha){
         $url = "https://www.google.com/recaptcha/api/siteverify?
                 secret=" . $secretKey . "&response=" . $recaptcha . 
                 "&remoteip=" . $_SERVER['REMOTE_ADDR'];

         $resource =  file_get_contents( $url ); 



        $val = json_decode($resource, true);
        if(intval($val["success"]) !== 1){
             echo "정상적인 접속이 아닌 것 같습니다.";
             die();
        }
         echo "name = $name <br />";

         echo "contents = $contents <br />";
     }else{
         echo "로봇이 아니면 체크해주세요.";
         die();
     }
 }
 ?> 
 <html>
     <head>
        <title>Google recapcha</title>         <script src='https://www.google.com/recaptcha/api.js'></script>

    </head>
    <body>
        <h1>Google reCAPTHA</h1>
        <form action="" method="post">         <input type="text" name="name" size="40"><br><br>         <textarea name="contents" rows="8" cols="40"></textarea><br><br>         <input type="submit" name="submit" value="Submit"><br><br>         <div class="g-recaptcha" data-sitekey="<?php echo $sitekey; ?>"></div>         </form>
     </body>
 </html>

0 댓글