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

本文详细介绍了Google的reCaptcha 2.0版本的使用方法,包括如何在Google账户中申请key,客户端设置及验证码验证的完整代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

登陆你的Google账户,没有的话是用不了的。

在这里来申请一对keyhttps://www.google.com/recaptcha/admin ,如下图

一个Google账户可以申请很多key,第一个label随便填,第二个是你的域名。我这里本地测试,直接输入localhost即可。

申请成功后可以看到两个key,一个是Site key,可以公开,一个是你自己的私key

Client端设置:随便写一个HTML网页,需要带一个form,用来提交表单。在表单内想显示验证码的地方输入

界面如图

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

 

这样的的主页将产生

 

验证完毕并提交表单后,将会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>

注意:在国内,需要翻墙的。其中道理你懂的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值