重新加载验证码问题

Reload captcha issues

本文关键字:验证 问题 加载 新加载      更新时间:2023-09-26

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

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

我想到的另一个问题是,验证码答案的代码会更新吗?如果没有,那么这是否意味着如果用户使用刷新链接,他们总是会收到验证码失败错误?

希夫

将其包含在 <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>

并且此代码出现在您希望验证码图像和刷新图标(获取合适的刷新图像并将其重命名为刷新.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']传递表单的其他值来检查用户输入和验证码中显示的文本是否匹配。

注意:不要忘记添加session_start();无论您想要验证码图像的任何地方。

很简单。只需在生成验证码的 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 文件最终实际返回的内容类型如何,都可以设置会话变量。