天天看点

如何使用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>