如何使用reCaptcha(2.0版本)来做网站验证码

reCaptcha是Google开发的验证码工具。使用十分简单,本文介绍的是其2.0版本的使用方法。 

  1. 登陆你的Google账户,没有的话是用不了的。
  2. 在这里来申请一对keyhttps://www.google.com/recaptcha/admin ,如下图

    一个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>

 

评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值