PHP将验证码保护添加到Web表单

时间:2020-01-09 10:42:59  来源:igfitidea点击:

如何判断PHP表单是由人还是脚本提交的?
您需要使用验证码,这只是您用来确保响应不是由机器人生成的一种质询-响应测试。
有很多为PHP提供的库。
我建议使用reCAPTCHA PHP库,该库提供了一种在您的PHP表单上放置验证码的简单方法。
它可以阻止机器人滥用它。
您需要使用reCAPTCHA API。

步骤1:获取reCAPTCHA API库

访问reCAPTCHA网站以注册API密钥(免费)。
请记下您的私钥和公钥。

步骤2:下载并安装reCAPTCHA PHP

从Google代码仓库下载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

步骤3:测试

创建一个php脚本,如下所示:

<html>
<head>
	<title>Sample Email Form</title>
</head>
<body>
 
 
<script>
    function checkForm() {
	if (document.forms.myphpform.elements['yname'].value.length == 0) {
		alert('Please enter a value for the "Name" field');
        	return false;
    	}
	if (document.forms.myphpform.elements['email'].value.length == 0) {
		alert('Please enter a value for the "Email" field');
        	return false;
    	}
	if (document.forms.myphpform.elements['message'].value.length == 0) {
		alert('Please enter a value for the "Message" field');
        	return false;
    	}
 
        return true;
   }
</script>
 
 
<form action="?done=1" method="post" name="myphpform" onSubmit="return checkForm()"  >
<table border=0>
	<tr>
		<td>Your Name:</td> <td><input type="text" name="yname" size="50" maxlength="50" value="" /></td>
	</tr>
 
	<tr>
		<td>Your Email:</td> <td><input type="text" name="email" size="50" maxlength="50" value="" /></td>
	</tr>
 
	<tr>
		<td>Message:</td> <td><input type="text" name="message" size="50" maxlength="50" value="" /></td>
	</tr>
	<tr>
		<td>Are you a human being?</td>
		<td>	
<?php
 
@require_once('recaptchalib.php');
$publickey = "YOUR-PUBLIC-KEY";
$privatekey = "YOUR-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="[email protected]";
	$subject="Feedback from example.com";
        $body=" Message via webform: 
 
Name: " .$_POST["yname"] . "\n
 
Email: " .$_POST["email"] . "\n
 
Message: " .$_POST["message"] . "\n";
        /*  send email */
	mail($to,$subject,$body);
	echo "<p>Email sent!</p>";
	exit(1);
 
  } else {
     	echo "Sorry cannot send email as you've failed to provide correct captcha! Try again...";
  }
}
echo recaptcha_get_html($publickey, $error);
?>
		<td/>
	</tr>
	<tr>
		<td> </td>
		<td><input type="submit" name="submit" value="submit" /></td>
	</tr>
</table>
</form>
</body>
</html>