July 14, 2009 – 10:13 pm
如何防止别人通过群发程序在你的网站上提交垃圾消息?这里将告诉你怎样用一个php表单做到这一点。
你需要使用Captcha,它是“Completely Automated Public Turing test to tell Computers and Humans Apart”(全自动区分计算机和人类的图灵测试)的缩写,是一种区分用户是计算机和人的公共全自动程序。
网上有很多PHP库文件你可以使用。我推荐reCAPTCHA PHP库文件,让你很容易就让你的PHP表单使用上CAPTCHA。通过调用reCAPTCHA API,你的表单可以让群发程序停止发垃圾信息了。
第一步: 获取reCAPTCHA API
在reCAPTCHA网站注册一个API key(免费)。并记录下你的private key和 public key。
第二步: 下载并安装reCAPTCHA PHP
从Google code上下载reCAPTCHA 库文件:
$ cd /tmp
$ wget http://recaptcha.googlecode.com/files/recaptcha-php-1.10.zip
解压recaptcha-php-1.10.zip, 回车:
$ unzip recaptcha-php-1.10.zip
最后, 将recaptchalib.php复制到你表单所在目录下面。
例如, 如果你的contact.php在/var/www/html目录下面, 像下面这样去复制recaptchalib.php:
$ cp /tmp/recaptcha-php-1.10/recaptchalib.php /var/www/html
第三步: 测试
创建一个php文件如下:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>简单的Email表单</title>
</head>
<body>
<script>
function checkForm() {
if (document.forms.myphpform.elements['yname'].value.length == 0) {
alert('请输入姓名');
return false;
}
if (document.forms.myphpform.elements['email'].value.length == 0) {
alert('请输入Email');
return false;
}
if (document.forms.myphpform.elements['message'].value.length == 0) {
alert('请输入内容');
return false;
}
return true;
}
</script>
<form action="?done=1" method="post" name="myphpform" onSubmit="return checkForm()" >
<table border=0>
<tr>
<td>姓名:</td>
<td>
<input type="text" name="yname" size="50" maxlength="50" value="" /></td>
</tr>
<tr>
<td>Email:</td>
<td>
<input type="text" name="email" size="50" maxlength="50" value="" /></td>
</tr>
<tr>
<td>内容:</td>
<td>
<input type="text" name="message" size="50" maxlength="50" value="" /></td>
</tr>
<tr>
<td>验证码:</td>
<td>
<?php
@require_once('recaptchalib.php');
$publickey = "YOUR-PUBLIC-KEY";//将你的PUBLIC-KEY放在这里
$privatekey = "YOUR-PRIVATE-KEY";//将你的PRIVATE-KEY放在这里
$resp = null;
$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) {
$to="you@example.com";//将你的邮箱放在这里
$subject="从 tips.wbwb.net 发来的留言";
$body=" 从Web表单发来的消息:
姓名: " .$_POST["yname"] . "\n
Email: " .$_POST["email"] . "\n
内容: " .$_POST["message"] . "\n";
/* 发送邮件 */
mail($to,$subject,$body);
echo "
Email 已经发送!
";
exit(1);
} else {
echo "对不起,发送失败,你没有输入正确的captcha! 请重试...";
}
}
echo recaptcha_get_html($publickey, $error);
?>
<td/>
</tr>
<tr>
<td> </td>
<td>
<input type="submit" name="submit" value="提交" /></td>
</tr>
</table>
</form>
</body>
</html>
本例运行截图如下:

你可以再这里看到最后的captcha运行效果。
(the end)
Posted in php | No Comments »