第一种方法:
首先在index.php页面
function identity(){
$this->load->view('index',$data);
}
function codes(){
if($_POST['code'] == $_SESSION['code']){
echo 'ok';
}else{
echo 'no';
}
}
function create_code(){
session_start();
//生成验证码图片
ob_clean();
//header("Content-type:image/png");
//全数字
$str="1,2,3,4,5,6,7,8,9,0,a,b,c,d,e,f";//要显示的字符,自己可以增加或删除
$list=explode(",",$str);
$r=count($list)-1;
$laststr="";
for($i=0;$i<4;$i++){
$randnum=mt_rand(0,$r);
$laststr .= $list[$randnum];//取出字符,组合成要显示的字符串
}
$_SESSION['code']=$laststr; //将字符串放入SESSION中
//echo $laststr;
$img=imagecreate(28,28);//生成图片
$black=imagecolorallocate($img,0,0,0); // 设置颜色
$white=imagecolorallocate($img,255,255,255);
$gray=imagecolorallocate($img,200,200,200);
$red=imagecolorallocate($img,255,0,0);
$cl = imagefill($img,0,0,$red);//给图片填充颜色
//将验证法放入图片
imagestring($img,4,10,8,$laststr,$black);//将验证码放到图片上
for ($i=0;$i<8;$i++){
$lineColor = imagecolorallocate($img,rand(0,255),rand(0,255),rand(0,255));
imageline ($img,rand(0,$x),0,rand(0,$x),$y,$lineColor);
}
//干扰点
for ($i=0;$i<250;$i++){
imagesetpixel($img,rand(0,$x),rand(0,$y),$fontColor);
}
$aa = imagepng($img);
$bb = imagedestroy($img);
//echo $aa;
}
在视图页面index.php
<form action="/index/codes" method="post">
<label for="yzmai" class="input-tips2">验证码:</label>
<input type="text" name="code" class="inputstyle2" maxlength="10" /><br/>
<img id="code" src="/index/create_code" alt="看不清楚,换一张" style="cursor: pointer; vertical-align:middle;" onClick="create_code()"/>
<button type="submit">提交</button>
</form>
<script>
function create_code(){
document.getElementById('code').src = '/index/create_code/'+Math.random()*10000;
}
</script>
可以去尝试下看看
第二种方法:
header("content-type:image/png");
ob_clean();
$img=imagecreate(44,18);
$bg=imagecolorallocate($img,245,245,245);//填充背景色
imagefill($img,0,0,$bg);//本函数将图片坐标 (x,y) 所在的区域着色。参数 col 表示欲涂上的颜色。
$vcode=" ";
for($i=0;$i<4;$i++)
{
$font_c=imagecolorallocate($img,6,6,6);//文本颜色
$num=rand(1,9);
$vcode=$vcode.$num;
imagestring($img,5,$i*10,1,$num,$font_c);//水平地画一行字符串
}
session_start();
$_SESSION['vcode']=$vcode;
imagepng($img); //imagepng — 以 PNG 格式将图像输出到浏览器或文件
imagedestroy($img);//销毁图像