0

我正在处理一个在提交之前用 jQuery 验证的表单。其中一个字段是验证码。

这个想法很简单,验证码显示为图像并存储在隐藏字段中。当用户在输入字段中输入验证码时,它应该等于隐藏字段的值。这是我拥有的 jQuery 代码;

<script>
$(document).ready(function(){
$("#register").validate({ 
errorElement: 'div', ignore: 'hidden',
rules: {
      password: { 
            required: true
      }, 
      password2: { 
            required: true, equalTo: "#password"
      },
      agree: {
          required: true
      },
      captcha: {
          required: true, equalTo: "#captcha2"
      }
  },
messages: {
password2: "Please repeat the same password",
captcha: "The captcha you entered is wrong",
agree: "You have to be at least 16 years old and agree to the terms of service" 
}
});
});
</script>

表单的 html 代码更简单,但我只展示其中的一部分。

<p>
<img src='/includes/captcha.php'  />
</p>
<p>
<label for="Captcha">Captcha</label>
<em> *</em><input type="text" name="captcha" id="captcha" size="25" 
class="require"   minlength="5" />
<input type="hidden" name="captcha2" id="captcha2" 
value="<?php echo    $_SESSION['captcha'];?>" />
<?php echo $_SESSION['captcha']; ?>

这里有一些奇怪的东西。当我回显 session['captcha'] 时,我得到的值与隐藏字段中的值不同。当我回显它时,我得到了以前的验证码。

因此,假设验证码值为 ABC。当我刷新页面时,验证码+隐藏字段变为 DEF。但是当我回显 session['captcha'] 时,我仍然得到 ABC。

为什么会这样?

这是captcha.php文件的代码;

<?php  
session_start();
header("Content-type: image/png");

$string = '';  
for ($i = 0; $i < 5; $i++) {  
// this numbers refer to numbers of the ascii table (lower case)  
$string .= chr(rand(97, 122));  
}  
$_SESSION['captcha']    =   $string;
putenv('GDFONTPATH=' . realpath('.'));
$dir = 'musicals';  
$image = imagecreatetruecolor(170, 60);  
$black = imagecolorallocate($image, 0, 0, 0);  
$color = imagecolorallocate($image, 129, 180, 79); // green  
$white = imagecolorallocate($image, 255, 255, 255);  
imagefilledrectangle($image,0,0,399,99,$white);  
imagettftext ($image, 30, 0, 10, 40, $color, $dir, $_SESSION['captcha']);  
imagepng($image);   
?>  
4

2 回答 2

0

问题是您的验证码生成在图像中,并且只有在访问表单后才能访问此图像。您的验证码是在您显示表单后生成的,这就是为什么它总是落后一步。

除此之外,将验证码解决方案存储在隐藏字段中是个坏主意。一个人,或者一个机器人,可以简单地解析网站的源代码并提取并使用它作为验证码解决方案。

于 2013-02-16T16:47:42.123 回答
0

确保 captcha.php 在 html 代码之前运行。看起来 captcha.php 生成图像,并且可能将其作为 img 插入 HTML。图片是在页面加载(生成 HTML)后获取的,因此不会重新生成会话中的验证码。

我相信您以验证码为例插入了隐藏元素。将验证码显示为表单中的隐藏元素是个坏主意。

于 2013-02-16T16:49:55.617 回答