reCAPTCHA 設定與使用

網路與網站相關議題和知識
回覆文章
dtchang
Site Admin
文章: 85
註冊時間: 2017-01-22, 16:54

reCAPTCHA 設定與使用

文章 dtchang » 2017-01-26, 11:17

首先 google: google reCAPTCHA
申請一組 site_key (公開) 和 secret_key (秘密)

define("RECAPTCHA_SITEKEY",'6Lfi9RIUAAAAAPoTqFLPoIrz_xxxxxxxxxxxx');
define("RECAPTCHA_SECRET",'6Lfi9RIUAAAAABROekSNCYzTDg1xxxxxxxxx');
define("RECAPTCHA_LANG",'zh-TW');

引用 JavScript
<script src="https://www.google.com/recaptcha/api.js" async defer></script>

顯示驗證圖(需使用到 site_key)(以示為配合 jQuery Mobile)
<div class="ui-field-contain">
<label for="recaptcha">驗&nbsp;&nbsp;證:</label>
<fieldset class="ui-grid-a">
<div id="recaptcha" class="g-recaptcha ui-block-a" data-sitekey="<?php echo RECAPTCHA_SITEKEY ?>">
若未顯示驗證圖,請重整網頁.
</div>
<div class="ui-block-b">
</div>
</fieldset>
</div>


驗證POST資料(驗證時需要到 secret_key)
//reCAPTCHA
$recaptcha_success = false;
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response']))
{
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/si ... e='.$_POST['g-recaptcha-response']);
$responseData = json_decode($verifyResponse);
if($responseData->success) $recaptcha_success = true;
}

當 $recaptcha_success 為 true,表示為驗證成功.

回覆文章