【问题标题】:Reload captcha issues重新加载验证码问题
【发布时间】:2014-04-05 14:10:46
【问题描述】:

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

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

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

湿婆

【问题讨论】:

  • 确保$_SESSION['string'] 在生成新的验证码时由image.php 更新,它应该可以工作。
  • 我不能这样做,因为内容类型设置为 image.php 上的图像
  • 不管内容类型是什么,如果是php文件你可以在里面设置会话变量。
  • 那我该如何更新呢?
  • 在 image.php 的某个地方,您正在生成一系列字母/数字作为验证码(我假设该变量称为 $captchaCode),然后从中创建图像。你只需做$_SESSION['string'] = $captchaCode;

标签: javascript php captcha reload


【解决方案1】:

<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)出现的任何位置。请记住此代码和上面的代码(在 &lt;script&gt; 标记内)应该在同一页面上,这样验证码才能正常工作。

<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']来检查用户输入和验证码中出现的文本是否匹配,无论你在哪里传递表单的其他值。

N。 B.:忘记添加 session_start();任何你想要验证码图像的地方。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2016-09-30
      • 2011-02-19
      • 2012-12-17
      • 2011-11-12
      • 2019-08-24
      • 2018-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多