
验证码的方法代码:
<?php
namespace Home\Controller;
use Think\Controller;
class PublicController extends Controller {
public function verify(){
session_start();
header("content-type:image/png");
$imageWidth = 76; //图像宽度
$imageHeight = 40; //图像高度
$length = 4; //字符串长度
$str = "QWERTYUIOPASDFGHJKLZXCVBNM0123456789"; //随机字符
$code = "";
for($i=0;$i<=$length;$i++){
$code.=$str[mt_rand(0,strlen($str)-1)];
}
$_SESSION['verify'] = $code; //把随机数验证码写入$code
$image = imagecreate($imageWidth,$imageHeight); //创建一个画布
imagecolorallocate($image,255,255,255); //验证码背景颜色
for($i=0;$i<strlen($_SESSION['verify']);$i++){ //循环输出个个验证
$font = mt_rand(3,5); //随机字体样式
$x = mt_rand(1,8)+$imageWidth*$i/4; //随机输出字符所在位置的x坐标
$y = mt_rand(8,$imageHeight/4); //随机输出字体所在位置的y坐标
//设置字符颜色
$color = imagecolorallocate($image,mt_rand(0,100),mt_rand(0,150),mt_rand(0,200));
imagestring($image,$font,$x,$y,$_SESSION['verify'][$i],$color); //水平输出字符
}
//绘制干扰点元素
$pixel = 30; //30个干扰点元素
$black = imagecolorallocate($image,0,0,0);
for($i=0;$i<$pixel;$i++){
imagesetpixel($image,mt_rand(0,$imageWidth-1),mt_rand(0,$imageHeight-1),$black);
}
imagepng($image);
imagedestroy($image);
}
}
调用方法的代码: public function verify(){
$Public = A('Public');
$verify = $Public->verify();
$this->display('verify');
}
verify.html这个模板是空的,因为生成了一张图片,不需要模板代码了登录界面引用的代码:
<td><input type="text" name="verify" class="input is-primary" placeholder="验证码" style="width:7.5em;"><img style="margin-left: 10px" src="verify.html" onclick="this.src=this.src+'?'+Math.random()"></td>
请问大神们为什么会出现乱码,是因为verify方法中的代码没有写好吗? 最佳答案
