我想在表单的onsubmit事件中获取会话captcha值,所以如果输入的文本与会话captcha数据不同,那么我将取消表单提交。问题是我无法准备好文档上的会话captcha值:
captcha生成的文件名为securitycode.php:
<?php
session_start();
$largeur = 120;
$hauteur = 40;
$longueur = 5;
$liste = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
$code = '';
$counter = 0;
$image = @imagecreate($largeur, $hauteur) or die('Impossible d''initializer GD')
;
for( $i=0; $i<10; $i++ ) {
imageline($image,
mt_rand(0,$largeur), mt_rand(0,$hauteur),
mt_rand(0,$largeur), mt_rand(0,$hauteur),
imagecolorallocate($image, mt_rand(200,255),mt_rand(200,255),mt_rand(200,255)
));
}
for( $i=0, $x=0; $i<$longueur; $i++ ) {
$charactere = substr($liste, rand(0, strlen($liste)-1), 1);
$x += 10 + mt_rand(0,10);
imagechar($image, mt_rand(3,5), $x, mt_rand(5,20), $charactere,
imagecolorallocate($image, mt_rand(0,155), mt_rand(0,155), mt_rand(0,155)));
$code .= $charactere;
}
header('Content-Type: image/jpeg');
imagejpeg($image);
imagedestroy($image);
$_SESSION['securecode'] = $code;
?>
在我的网页上,我创建了图像captcha:
...
<img id="captcha_img" src="securitecode.php" />
<input type="text" id="captcha" />
<span id="msg_captcha"></span>
...
<script type="text/javascript">
$(document).ready(function() {
$('#msg_captcha').html("<?php echo $_SESSION['securecode']; ?>");
});
</script>
当页面第一次加载时,#msg_captcha跨度内没有显示任何内容!那么如何获取captcha会话数据呢?
这是因为会话的工作方式
当会话结束并且会话数据已写入会话文件时,会话值可用。
在请求页面时,您实际上试图获得一个尚未设置的会话值,原因有两个。
-
captcha图像是在您的初始请求之后加载的,但PHP已经处理了
<?php echo $_SESSION['securecode']; ?>
部分。 -
$_SESSION['securecode']
值是在加载图像之后写入的。
因此,基本上,您的解决方案试图过早地读取值。
解决方案
使用AJAX检查captcha代码,或者在下一个请求中验证captcha码。
Javascript不能以这种方式运行PHP。PHP是服务器端语言,javascript是客户端语言。也许这个话题可以帮助你。