方便简单的image验证码类
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
//-------------------------------------
// 文件说明:生成验证码
//-------------------------------------
class image{
function get() {
session_start();
session_register('vdcode');
//不存在imageCreate函数则认为当前环境不支持GD库
if (function_exists('imagecreate')) {
//产生4个字符的随机字符串作为验证码
$str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
$code = array();
for ($i=0; $i<4; $i++) {
$code[] = $str;
}
//将验证码写入到Session,忽略大小写
$_SESSION['vdcode'] = strtolower(implode('',$code));
$width = 50; //图片宽度
$height = 20; //图片高度
$im = ImageCreate($width,$height); //创建图形
ImageColorAllocate($im,255,255,255); //填充背景颜色为白色
//用淡色给图形添加杂色
for ($i=0; $i<100; $i++) {
$pxcolor = ImageColorAllocate($im,mt_rand(100,255),mt_rand(100,255),mt_rand(100,255));
ImageSetPixel($im,mt_rand(0,$width),mt_rand(0,$height),$pxcolor);
}
//用深色调绘制边框
$bordercolor = ImageColorAllocate($im,mt_rand(0,100),mt_rand(0,100),mt_rand(0,100));
ImageRectangle($im,0,0,$width-1,$height-1,$bordercolor);
//用比较明显的颜色写上验证码文字
$offset = 5;
foreach ($code as $char) {
$textcolor = ImageColorAllocate($im,mt_rand(0,250),mt_rand(0,150),mt_rand(0,250));
ImageChar($im,5,$offset,2,$char,$textcolor);
$offset += 10;
}
//禁止缓存
header("pragma:no-cache\r\n");
header("Cache-Control:no-cache\r\n");
header("Expires:0\r\n");
//检查系统支持的文件类型,优先级为PNG->JPEG->GIF
if (ImageTypes() & IMG_PNG) {
header('Content-Type:image/png');
ImagePNG($im);
} elseif (ImageTypes() & IMG_JPEG) {
header('Content-Type:image/jpeg');
ImageJPEG($im);
} else {
header('Content-Type:image/gif');
ImageGif($im);
}
} else {
//不支持GD库,则输出默认验证码ABCD
$_SESSION['vdcode'] = 'abcd';
header('Content-Type:image/jpeg');
$fp = fopen('vdcode.jpg','rb');
return fread($fp,filesize('vdcode.jpg'));
fclose($fp);
}
}
}
?>
image图片页面
只需要在任一控制器里写一个就行了
function image() {
$this->load->library('image');
echo $this->image->get();
}
需要的时候在图片地址写上 src='image'就行了,
空了改下...
咋不高亮了,我用了这个哈,,麻烦BB代码整下... 我已经帮你修改了语法加亮,呵呵~~ 谢谢BB,:lol
加什么标签?
我加 不行.... 楼主的贴子真好,谢谢
测试使用的时候有时候有一定的机率会出现错误
A PHP Error was encounteredSeverity: NoticeMessage: Uninitialized string offset: 62
Filename: libraries/image.php
Line Number: 16
A PHP Error was encounteredSeverity: Warning
Message: Cannot modify header information - headers already sent by (output started at E:\Discuz!EXP\wwwroot\Code\system\libraries\Exceptions.php:164)
Filename: libraries/image.php
Line Number: 40 session怎么取不到啊 能啊,,这是我项目中用过的,,, 为什么我的在HTML上显示的是个叉啊? 我查了 引用没错啊 我换了个验证码程序也显示的是个叉 不知道怎么搞的 高手帮忙解决啊!!!! 为什么我一用到这个类,我的apache就挂了? Severity: Warning
Message: session_start() : Cannot send session cookie - headers already sent by (output started at F:\PHP\WWW\CI\system\application\libraries\Image.php:1)
Filename: libraries/Image.php
完全按照说明来的
我的controller
<?php
class Imgextends Controller {
function img()
{
parent::Controller();
}
function index()
{
$this->load->library('image');
echo $this->image->get();
}
}
文件的bom也去掉了啊。
页:
[1]
2