PHP使用reCAPTCHA作为验证码来保护您的网站
date:星期一, 三月 15th, 2010 at 6:02 下午 Categories:php
CAPTCHA,其全称是“全自动区分计算机和人类的图灵测试”(completely automated public Turing test to tell computers and humans apart)。
现在通过使用 Google免费的reCAPTCHA服务,您可以轻松地在您自己的网站上利用这项技术。
首先
我们需要申请一个 KEY
类似于GOOGLE MAP的API KEY一样
在reCAPTCHA网站注册一个API key(免费)。并记录下你的private key和 public key。
https://admin.recaptcha.net/accounts/signup/
然后去GOOGLE CODE 下载类库
http://code.google.com/p/recaptcha/downloads/list?q=label:phplib-Latest
调用类
require_once('recaptchalib.php'); $publickey = "..."; // you got this from the signup page echo recaptcha_get_html($publickey);
验证部分
require_once('recaptchalib.php'); $privatekey = "..."; $resp = recaptcha_check_answer ($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]); if (!$resp->is_valid) { die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." . "(reCAPTCHA said: " . $resp->error . ")"); }
官方还提供了一个 EXAMPLE
<html>
<body>
<form action="" method="post">
<?php
require_once('recaptchalib.php');
$publickey = "...";
$privatekey = "...";
# the response from reCAPTCHA
$resp = null;
# the error code from reCAPTCHA, if any
$error = null;
# are we submitting the page?
if ($_POST["submit"]) {
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if ($resp->is_valid) {
echo "You got it!";
# in a real application, you should send an email, create an account, etc
} else {
# set the error code so that we can display it. You could also use
# die ("reCAPTCHA failed"), but using the error message is
# more user friendly
$error = $resp->error;
}
}
echo recaptcha_get_html($publickey, $error);
?>
<br/>
<input type="submit" name="submit" value="submit" />
</form>
</body>
</html>