1. 程式人生 > >如何使用reCaptcha(2.0版本)來做網站驗證碼

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

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

  1. 登陸你的Google賬戶,沒有的話是用不了的。
  2. 在這裡來申請一對key ,如下圖

    一個Google賬戶可以申請很多key,第一個label隨便填,第二個是你的域名。我這裡本地測試,直接輸入localhost即可。
  3. 申請成功後可以看到兩個key,一個是Site key,可以公開,一個是你自己的私key
  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 lang="en">
    <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>


    這樣的的主頁將產生

    點選藍色的方框即可開始驗證

    如果sitekey與域名不匹配的話會顯示

  5. 驗證完畢並提交表單後,將會post一個g-recaptcha-response 值。這個值用來和Google伺服器通訊驗證驗證碼是否正確。

    將這個值通過post方式傳送到 https://www.google.com/recaptcha/api/siteverify 將獲得一個jason格式結果,如下:

    即完成了驗證。
    下面附上完整的驗證程式碼

    <span style="font-size:14px;"><!DOCTYPE html>
    <html lang="en">
    <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>