PHP和JS - 创建验证码

时间:2018-01-29 15:38:59

标签: javascript php

我在创建简单的验证码方面遇到了一些麻烦。 我有一个按钮,其中显示验证码,如果用户点击它,它应该显示另一个验证码。问题是没有任何反应。 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

1 个答案:

答案 0 :(得分:0)

你可以尝试这个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;

我希望它能解决你的问题