laravel中如何写验证码文件,并防止中文乱码.

本例为生成中文验证码,专为laravel而生.

//控制器:
public function getVcode(Request $request){
        $width=845;
        $height=125;
        $fp=fopen(url('/').'/front/register/chengyu.txt','r');//打开本地文件,里面存了150条成语!一行一条.
        $hang=rand(0,149);
        for($i=0;;$i++){
            $get=fgets($fp);
            if($i==$hang)
                break;
        }
        $text=$get;//得到的成语字符串
        header('content-type:image/jpeg');
        //1、创建画布
        $img = imagecreatetruecolor($width,$height);
        //1-1、背景颜色随机 0~125深色   126~255 浅色
        $bgColor = imagecolorallocate($img,rand(126,255),rand(126,255),rand(126,255));
        imagefill($img,0,0,$bgColor);
        //2、写字或画画
        //2-1、画点点
        for($i = 0 ; $i <= ($height*$width/15) ; $i++){
            $pixX = rand(5,$width-5);//随机x的位置
            $pixY = rand(5,$height-5);//随机的Y的位置
            $pixColor = imagecolorallocate($img,rand(0,125),rand(0,125),rand(0,125));
            imagesetpixel($img,$pixX,$pixY,$pixColor);
        }
        //2-2、写字
        
        $code = 'abcdefghijklmnopqrstuvwxyz';
         $len = mb_strlen($text,'UTF-8');
        for($j = 1 ; $j <= 4 ; $j++){
            //字体大小随机从15像素~20像素
            $fontSize = rand(($height/2-5),($height/2+10));
            //x的位置
            $fontX = ($width/ 4) * ($j-1);//25 50 75 100
            //Y的位置
            $fontY = $height*0.75;
            //字体颜色
            $fontColor = imagecolorallocate($img,rand(0,125),rand(0,125),rand(0,125));
            //每次随机出来的字

            $fontText = mb_substr($text,$j-1,1,'UTF-8');//读取一个汉字
            //echo $fontText;
            imagettftext($img,$fontSize,0,$fontX,$fontY,$fontColor,$_SERVER['DOCUMENT_ROOT'].'/front/register/FZSTK.TTF',$fontText);
        }
        //3、输出或保存
        imagejpeg($img);
        //4、解析模板
        view('front.register.showvcode',['dd'=> imagejpeg($img)]);
    //5销毁资源
     image_destroy($img); }

  主要 解决以下一个问题:

1 laravel路由和模板文件自行设计.

2 fopen打开public目录下的文件:

 $fp=fopen(url('/').'/front/register/chengyu.txt','r');

3 截取汉字,utf8格式,使用mb_substr

mb_substr($text,$j-1,1,'UTF-8');

4 ttf文件访问

$_SERVER['DOCUMENT_ROOT'].'/front/register/FZSTK.TTF'

5 变量带到模板

['dd'=> imagejpeg($img)]

6 文件保存为utf-8无bom格式,以及注意TTF到底是要输出英文还是中文!!不要搞错.

原文地址:https://www.cnblogs.com/zxj95121/p/6024051.html