由于WordPress没有自带验证码功能(应该啦),并且我又被某些大佬安排过(刷评论),所以,我准备直接在博客里面加入reCAPTCHA验证。废话不多说,我们开始
1、首先进入 https://www.google.com/recaptcha/admin/create 新建你的站点,然后你会得到两个Key
一个是前端的,一个是后端的
2、在页面中需要的地方添加下方js代码块(仅为示例,请自行优化代码)
<script src=”https://recaptcha.net/recaptcha/api.js” type=”text/javascript” async defer></script> <div class=”g-recaptcha” data-sitekey=”{刚才获得的网站密钥,不是通信密钥}” data-callback=”{这个是验证完成之后的回调,好像也可以不加}”></div>
3、在后端的接收端,加下方代码
function getCaptcha() { $captcha = $_POST[‘g – recaptcha – response’]; if (isset($captcha)) { if (”!= $captcha) { //开始验证 $url =”https://www.google.com/recaptcha/api/siteverify”; $data = array( ‘secret’=> ‘{这里填写后端密钥,就是下面那个}’, ‘response’=> $captcha ); $options = array( ‘http’=> array( ‘header’=> ’Content – type: application / x – www – form – urlencoded’, ‘method’=> ’POST’, ‘content’=> http_build_query($data) ) ); $context = stream_context_create($options); $result = file_get_contents($url, false, $context); //向Google服务器发出请求 $response = json_decode($result); if (!($response -> success)) { return false; } } else { return false; //验证没过 } } else { return false; //参数为空(可能访客手动删除了验证模块) } return true; }
发表评论