PHP之后台验证码的实现
<?php
//验证码的实现
//
//生成码值
$chars='ABCDEFGHIJKLMNOPQRST123456789';
$chars_len=strlen($chars);
$code_len=4;//码值得长度
$code='';//初始化码值字符串
for($i=1;$i<=$code_len;++$i){
$rand_index=mt_rand(0,$chars_len-1);//获取随机数
$code.=$chars[$rand_index];//字符串支持[]操作,通过下标取得某个字符
}
session_start();
$_SESSSION['captcha_code']=$code;
//生成验证码图片
//背景图片
$bg_file='./captcha/captcha_bg'.mt_rand(1,5).'.jpg';
//基于JPG格式的图片创建画布
$img=imagecreatefromjpeg($bg_filr);
//随机分配文字颜色
$str_color=mt_rand(1,2)==1?imagecolorallocate($img, 0, 0, 0):imagecolorallocate($img,0xff,0xff,0xff);
$font=5;//内部字体用1到5 表示,1小,5最大,
//计算画布大小
$img_w=imageSX($img);//画布宽
$img_h=imageSY($img);//画布高度
imageFontWidth($font);//字体宽度,括号中是字体号数
imagefontheight($font);//字体高度
//字符串的尺寸
$code_w=$font_w*$code_len;
$code_h=$font_h;
$x=($img_w-$code_w)/2;
$y=($img_h-$code_h)/2;
imageString($img,$font,$x,$y,$code,$str_color);//参数一次是:画布,字体大小,最左边字体的x,最左边字体的y,字符串,字符串颜色
//输出画布
header('Content-Type:image/jpeg;');
imageJPEG($img);
//销毁画布
//验证码的实现
//
//生成码值
$chars='ABCDEFGHIJKLMNOPQRST123456789';
$chars_len=strlen($chars);
$code_len=4;//码值得长度
$code='';//初始化码值字符串
for($i=1;$i<=$code_len;++$i){
$rand_index=mt_rand(0,$chars_len-1);//获取随机数
$code.=$chars[$rand_index];//字符串支持[]操作,通过下标取得某个字符
}
session_start();
$_SESSSION['captcha_code']=$code;
//生成验证码图片
//背景图片
$bg_file='./captcha/captcha_bg'.mt_rand(1,5).'.jpg';
//基于JPG格式的图片创建画布
$img=imagecreatefromjpeg($bg_filr);
//随机分配文字颜色
$str_color=mt_rand(1,2)==1?imagecolorallocate($img, 0, 0, 0):imagecolorallocate($img,0xff,0xff,0xff);
$font=5;//内部字体用1到5 表示,1小,5最大,
//计算画布大小
$img_w=imageSX($img);//画布宽
$img_h=imageSY($img);//画布高度
imageFontWidth($font);//字体宽度,括号中是字体号数
imagefontheight($font);//字体高度
//字符串的尺寸
$code_w=$font_w*$code_len;
$code_h=$font_h;
$x=($img_w-$code_w)/2;
$y=($img_h-$code_h)/2;
imageString($img,$font,$x,$y,$code,$str_color);//参数一次是:画布,字体大小,最左边字体的x,最左边字体的y,字符串,字符串颜色
//输出画布
header('Content-Type:image/jpeg;');
imageJPEG($img);
//销毁画布
imageDestroyed($img);
=================图片错误解析==========
图片输出出错原因,有额外的输出,不能有echo,PHP标签外不能有空格;