在PHP4中Zend没有完全引入对OOP的支持,但是已经可以实现一些类的特性了,下面就是我写的生成验证码图片的类,说是类,其实就是用类的形式封装起来的过程,很初级的实现:
<?php
class check_code {
var $img_size_x; //图片大小参数
var $img_size_y;
var $shape; //背景用什么形状做“干扰”
var $shape_num; //“干扰”图形的数量
var $case_sensitive; //是否大小写区分
var $char_str; //返回的验证码值,用于验证
function check_code($pos_x,$pos_y,$bg_shape,$shape_num,$case_sensitive) {
//构造函数,需要提供以上变量的信息
$this->img_size_x = $pos_x;
$this->img_size_y = $pos_y;
$this->shape = $bg_shape;
$this->shape_num = $shape_num;
$this->case_sensitive = $case_sensitive;
$this->char_str = ”;
}
function draw() { //创建并显示图片
$bgim = imagecreate($this->img_size_x,$this->img_size_y);
$gray = imagecolorallocate($bgim,240,240,240);
$black = imagecolorallocate($bgim,0,0,0);
imagerectangle($bgim,0,0,$this->img_size_x-1,$this->img_size_y-1,$black);
for($i = 0; $i < $this->shape_num; $i++)
{
$shape_x = rand(0,$this->img_size_x);
$shape_y = rand(0,$this->img_size_y);
$rand_color = imagecolorallocate($bgim,rand(150,255),rand(150,255),rand(150,255));
imagestring($bgim,2,$shape_x,$shape_y,$this->shape,$rand_color);
}
for($i = 0; $i < 4; $i++)
{
$char = $this->char_gen();
$this->char_str .= $char;
$char_x = rand(10+(int)($this->img_size_x-20)/4*$i,(int)(($this->img_size_x-20)/4)*($i+1));
$char_y = rand(10,(int)($this->img_size_y-10)/2);
imagestring($bgim,5,$char_x,$char_y,$char,$black);
}
if($this->case_sensitive == FALSE)
$this->char_str = strtolower($this->char_str);
//可以将验证的字符串放到cookie或者session
header(“Content-type: image/png”);
imagepng($bgim);
imagedestroy($bgim);
}
function char_gen(){ //创建随机数,包括大小写字母和数字
$type = rand(0,2);
switch($type){
case 0:
return rand(0,9);
break;
case 1:
$char = rand(65,90);
$char = chr($char); //由ascii码转换成字符
return $char;
break;
case 2:
$char = rand(97,122);
$char = chr($char);
return $char;
break;
}
}
}
?>
参考了网上的一些其他类似程序,有些只能生成数字,有的用十六进制生成有限的几个字母,我这个就字符生成这点来看,好像还算是比较完整的。
本段代码需要GD库支持。