lavarel之原生验证码使用

因为laravel对header头部作了处理,很多原生图片生成的写法,在laravel都不适用了,需要换种写法

以下这是原生php的写法,在普通php文件中,和tp框架中都可以正常输出验证码

           session_start();
            $tatted_code=dechex(mt_rand(0,15));
            for($i=0;$i<3;$i++){
                $tatted_code.=dechex((mt_rand(0,15)));
            }
            $_SESSION['code']=$tatted_code;
            $width=70;
            $height=25;
            $img=imagecreatetruecolor($width, $height);
            $_white=imagecolorallocate($img,236,251,208);
            
            imagefill($img,0,0,$_white);
            $bg=imagecolorallocate($img,204,204,204);
            imagerectangle($img,0,0,$width-1,$height-1,$bg);
            for($i=0;$i<strlen($_SESSION['code']);$i++){
                   
                      imagestring($img,mt_rand(3,5),$i*$width/4+mt_rand(1,10),mt_rand(1,$height/2),$_SESSION['code'][$i],
                    imagecolorallocate($img,mt_rand(0,100),mt_rand(50,150),mt_rand(100,200)));
            }
            //输出图像
            header('Content-Type:image/png');
            imagepng($img);
            imagedestroy($img);

以上的写法,在laravel中是不适用的,会导致出现一大堆的乱码,原因是laravel对header进行了处理。
以下代码,是laravel5.2中的写法,其他版本也类似

Route::get('verify',function(){
    ob_clean();
    ob_start();
    session_start();
    $tatted_code=dechex(mt_rand(0,15));
    for($i=0;$i<3;$i++){
        $tatted_code.=dechex((mt_rand(0,15)));
    }
    $_SESSION['code']=$tatted_code;
    $width = 70;
    $height = 25;
    $img = imagecreatetruecolor($width, $height);
    $_white = imagecolorallocate($img,236,251,208);
            
    imagefill($img,0,0,$_white);
    $bg = imagecolorallocate($img,204,204,204);
    imagerectangle($img,0,0,$width-1,$height-1,$bg);
    for($i=0;$i<strlen($_SESSION['code']);$i++){
        imagestring($img,mt_rand(3,5),$i*$width/4+mt_rand(1,10),mt_rand(1,$height/2),$_SESSION['code'][$i],
        imagecolorallocate($img,mt_rand(0,100),mt_rand(50,150),mt_rand(100,200)));
    }
    imagepng($img);
    imagedestroy($img);
    $content = ob_get_clean();
    return response($content)->header('Content-Type','image/png');
});
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,421评论 19 139
  • 原文链接 必备品 文档:Documentation API:API Reference 视频:Laracasts ...
    layjoy阅读 8,689评论 0 121
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 178,096评论 25 709
  • 没有8心8箭50克拉的铂金钻戒,999999朵玫瑰和300万以上的顶配豪车……怎么求婚? 年轻人!作为过来人,我实...
    C老师碎碎念阅读 467评论 0 1
  • 这是个与世隔绝,繁华而冷清的世界,到处都是漫无目的的行走着的代码人----由一段段记忆代码组成的人。 “fir...
    哈哈1203阅读 950评论 1 5

友情链接更多精彩内容