繁体   English   中英

PHP和JS-创建验证码

[英]PHP and JS - Creating captcha

我在创建简单的验证码时遇到了麻烦。 我有一个显示验证码的按钮,如果用户单击它,则应该显示另一个验证码。 问题是什么也没发生。 PHP生成了验证码,但似乎未触发onclick事件。 有什么建议吗?

我的PHP代码:

$random_alpha = md5(rand());
$captcha_code = substr($random_alpha, 0, 6);
$_SESSION['CAPTCHA_CODE'] = $captcha_code;
$im = @imagecreatetruecolor(70,30);

imagesavealpha($im, true);
imagealphablending($im, false);

$white = imagecolorallocatealpha($im, 255, 255, 255, 127);
imagefill($im, 0, 0, $white);

$lime = imagecolorallocate($im, 204, 255, 51);
$captcha_text_color = imagecolorallocate($im, 0, 0, 0);
imagestring($im, 5, 5, 5, $captcha_code, $captcha_text_color);
header("Content-type: image/png");
imagepng($im);
imagedestroy($im);

我的JS:

<script>
    function refreshCaptcha() {
        event.preventDefault();
        $("#captcha_code").attr('src', './controllers/captcha.php');
    }
</script>  

我的HTML:

<button onclick="refreshCaptcha();" class="btn btn-block btn-hero btn-noborder btn-rounded btn-alt-info" id="captcha" name="captcha">
  <i class="si si-refresh mr-10"></i><img id="captcha_code" src="../controllers/captcha.php" />
</button>  

如果我手动刷新页面,它将创建一个新的验证码,因此我知道它可以正常工作。 我的错误在哪里?

谢谢!

编辑:我认为这可能与我在PHP中的会话有关。 我使用以下代码来生成会话:

$session_name = 'THA_SESSION';   // Set session name
$secure = false;
// Avoid JS to access session info
$httponly = true;
// Force session to use cookies
if (ini_set('session.use_only_cookies', 1) === FALSE) {
    header("Location: ./errno.php");
    exit();
}
// Get the cookie params
$cookieParams = session_get_cookie_params();
session_set_cookie_params($cookieParams["lifetime"],
    $cookieParams["path"], 
    $cookieParams["domain"], 
    $secure,
    $httponly);
// Set the session with the name defined above
session_name($session_name);
session_start();            // starts session

您可以尝试此js代码

function refreshCaptcha() {
    event.preventDefault();
    $.ajax({
        url: 'captua.php',
        method: 'GET',
        success: function (data){
            $('#captcha_code').attr('src','data:image/png;base64,'+data);
        },
    });
}

    ob_start();
    $random_alpha = md5(rand());
    $captcha_code = substr($random_alpha, 0, 6);
    $_SESSION['CAPTCHA_CODE'] = $captcha_code;
    $im = @imagecreatetruecolor(70,30);

    imagesavealpha($im, true);
    imagealphablending($im, false);

    $white = imagecolorallocatealpha($im, 255, 255, 255, 127);
    imagefill($im, 0, 0, $white);

    $lime = imagecolorallocate($im, 204, 255, 51);
    $captcha_text_color = imagecolorallocate($im, 0, 0, 0);
    imagestring($im, 5, 5, 5, $captcha_code, $captcha_text_color);
    header("Content-type: image/png");
    imagepng($im);
    imagedestroy($im);
    $captchaImageData=ob_get_contents();
    ob_end_clean();
    $encodedData = base64_encode($captchaImageData);
    echo $encodedData;

希望它能解决您的问题

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM