天天看點

如何使用reCaptcha(2.0版本)來做網站驗證碼

reCaptcha是Google開發的驗證碼工具。使用十分簡單,本文介紹的是其2.0版本的使用方法。 

  1. 登陸你的Google賬戶,沒有的話是用不了的。
  2. 在這裡來申請一對keyhttps://www.google.com/recaptcha/admin ,如下圖
    如何使用reCaptcha(2.0版本)來做網站驗證碼
    一個Google賬戶可以申請很多key,第一個label随便填,第二個是你的域名。我這裡本地測試,直接輸入localhost即可。
  3. 申請成功後可以看到兩個key,一個是Site key,可以公開,一個是你自己的私key
    如何使用reCaptcha(2.0版本)來做網站驗證碼
  4. Client端設定:随便寫一個HTML網頁,需要帶一個form,用來送出表單。在表單内想顯示驗證碼的地方輸入
    <span style="font-size:14px;">        <div class="g-recaptcha" data-sitekey="Yoursitekey"></div></span>
               
    在</head>前輸入
    <span style="font-size:14px;"><script src='https://www.google.com/recaptcha/api.js'></script></span>
               
    如下:
    <span style="font-size:14px;"><!DOCTYPE html>
    <html >
    <head>
        <title></title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        
        <script src='https://www.google.com/recaptcha/api.js'></script>
    </head>
    <body>
    
        <form action="confirm.php" method="post">
            <div class="g-recaptcha" data-sitekey="yoursitekey"></div>
            
            <p><button class="btn btn-primary" type="submit">Register</button>
        </form>
    </body>
    </html>
    </span>
               
    這樣的的首頁将産生
    如何使用reCaptcha(2.0版本)來做網站驗證碼
    點選藍色的方框即可開始驗證
    如何使用reCaptcha(2.0版本)來做網站驗證碼
    如果sitekey與域名不比對的話會顯示
    如何使用reCaptcha(2.0版本)來做網站驗證碼
  5. 驗證完畢并送出表單後,将會post一個g-recaptcha-response 值。這個值用來和Google伺服器通信驗證驗證碼是否正确。
    如何使用reCaptcha(2.0版本)來做網站驗證碼
    将這個值通過post方式發送到 https://www.google.com/recaptcha/api/siteverify 将獲得一個jason格式結果,如下:
    如何使用reCaptcha(2.0版本)來做網站驗證碼

    即完成了驗證。

    下面附上完整的驗證代碼

    <span style="font-size:14px;"><!DOCTYPE html>
    <html >
    <head>
        <title></title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <?php
    function send_post($url, $post_data)
    {
        $postdata = http_build_query($post_data);
        $options = array(
            'http' => array(
                'method' => 'POST',
                'header' => 'Content-type:application/x-www-form-urlencoded',
                'content' => $postdata,
                'timeout' => 15 * 60 // 逾時時間(機關:s)
            )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        return $result;
    }
    		    
    $post_data = array(        
    'secret' => 'yoursecretkey',        
    'response' => $_POST["g-recaptcha-response"]    );
        $recaptcha_json_result = send_post('https://www.google.com/recaptcha/api/siteverify', $post_data);   
     $recaptcha_result = json_decode($recaptcha_json_result);   
    //在這裡處理傳回的值 
    //var_dump($recaptcha_result);    
    ?>
    </head>
    <body>
    echo $recaptcha_result;
    </body>
    </html>
    
    	</span>