重新加载验证码问题

时间:2014-04-05 14:10:46

标签: javascript php captcha reload

我正在使用此代码:http://pastebin.com/Q9RXLZEd作为我的注册页面。我试图让验证码重新加载。验证码是PHP文件代码的正常制作图像,内容类型是PNG图像。

我目前的代码没有验证码刷新或任何东西。

我想到的另一个问题是,验证验证码答案的代码是否会更新?如果它没有,那么这是否意味着如果用户使用刷新链接,用户将始终获得验证码失败错误?

希夫

2 个答案:

答案 0 :(得分:0)

简单。只需将随机参数添加到生成验证码的PHP文件的URL(例如image.php?param=randomvalue)。这样你就可以绕过验证码图像的缓存。

重新加载验证码的代码可能是这样的:

$("#refreshLink").click(function(){
    // Create some random string consisting of numbers
    var random = (Math.random() + "").substring(2);
    // Load a new captcha image by updating the image's src attribute
    $("#refresh img").attr("src", "image.php?param=" + random);
});

您还需要稍微调整HTML代码:

<tr>
    <td>Captcha:</td>
    <td><div id='refresh'><img src='image.php'></div></td>
    <td><a id='refreshLink'>Refresh</a></td>
</tr>


关于你问题的第二部分:正如@James已经说过 - 如果image.php每次请求文件时都正确设置$_SESSION['string'],那么用户就不会获得验证码错误,因为变量只在表格已提交。无论PHP文件最终实际返回的内容类型如何,都可以设置会话变量。

答案 1 :(得分:0)

<head>标记中包含此内容     

<script type="text/javascript">
$(document).ready(function() { 

 // refresh captcha
 $('img#captcha-refresh').click(function() {  

        change_captcha();
 });

 function change_captcha()
 {
    document.getElementById('captcha').src="captcha.php?rnd=" + Math.random();
 }

});


</script>

此代码可以显示验证码图像和刷新图标(获取合适的刷新图像并将其重命名为refresh.jpg)。请记住此代码,上面的代码(在<script>标记内)应该在同一页面上,以便验证码工作。

<img src="captcha.php" alt="" id="captcha" />
Type the word:
 <input name="user_captcha" type="text" id="captcha-code">
 <img src="refresh.jpg"  alt="" id="captcha-refresh" />

然后创建一个名为captcha.php的文件(它按照要求生成png格式的验证码图像。)

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

$word_1 = '';

for ($i = 0; $i < 4; $i++) 
{
    $word_1 .= chr(rand(97, 122));
}

$_SESSION['random_number'] = $word_1;


$dir = "./";
$image = imagecreatetruecolor(165, 50);

$font = "whatever.ttf"; // font style you may give any you have / prefer

$color = imagecolorallocate($image, 0, 0, 0);// color

$white = imagecolorallocate($image, 255, 255, 255); // background color white

imagefilledrectangle($image, 0,0, 709, 99, $white);

imagettftext ($image, 22, 0, 45, 30, $color, $dir.$font, $_SESSION['random_number']);

imagepng($image);  
?>

最后,您必须通过比较$_POST['user_captcha']$_SESSION['random_number'],无论您在何处传递表单的其他值,都要检查用户输入和验证码中显示的文本是否匹配。

<磷>氮。 B。: NOT 忘记添加session_start();无论你想要什么样的验证码图像。

相关问题