美文网首页
PHP生成图片验证码

PHP生成图片验证码

作者: BiaoWong | 来源:发表于2018-12-05 09:37 被阅读7次

后台代码

生成验证码

/**
 * 获取验证码
 * @author wangbiao <biaowong@qq.com>
 */
public function verifycode($param=null)
{
    $w = 100;   // 宽
    $h = 30;    // 高

    $img = imagecreate($w, $h);

    $red = imagecolorallocate($img, 255, 0, 0);
    $white = imagecolorallocate($img, 255, 255, 255);

    $num1 = rand(1, 20);
    $num2 = rand(1, 20);

    // Session::flash('captcha_math', $num1 + $num2); // 一次性使用
    Cookie::queue('captcha_math', $num1 + $num2, 10); // 10 分钟
    // Cookie::queue('captcha_math', null , -1);      // 销毁
    $gray = imagecolorallocate($img, 118, 151, 199);
    $black = imagecolorallocate($img, mt_rand(0, 100), mt_rand(0, 100), mt_rand(0, 100));

    // 画背景
    imagefilledrectangle($img, 0, 0, $w, $h, $black);
    // 在画布上随机生成大量点,起干扰作用;
    for ($i = 0; $i < 80; $i++) {
        imagesetpixel($img, rand(0, $w), rand(0, $h), $gray);
    }

    imagestring($img, 5, 5, 4, $num1, $red);
    imagestring($img, 5, 30, 3, "+", $red);
    imagestring($img, 5, 45, 4, $num2, $red);
    imagestring($img, 5, 70, 3, "=", $red);
    imagestring($img, 5, 80, 2, "?", $white);

    header("Content-type: image/png");
    imagepng($img);
    imagedestroy($img);
    die;
}

判断验证码

if (Cookie::get('captcha_math') != $userinput) {
    return '验证码错误!';
}

Route

Route::get('verifycode.html/{param?}', 'UserController@verifycode');

前端代码

<div class="fr getCode"><img id="verifycode_src" src="{{ url('verifycode.html') }}" alt="获取验证码" class="codes"></div>

JavaScript

$('.getCode').click(function () {
    $('#verifycode_src').attr('src', "/verifycode.html/" + Math.random());
})

展示效果

验证码 效果图验证码 效果图

相关文章

网友评论

      本文标题:PHP生成图片验证码

      本文链接:https://www.haomeiwen.com/subject/rbficqtx.html