PHP验证码

来源:互联网 发布:重大人生启示录 知乎 编辑:程序博客网 时间:2024/06/05 07:24

 <?php

 
/***********************************************
 *   *
 * @验证码类   *
 * @版本   1.0   *
 * @作者   军   *
 * @时间   2010-07-02   *
 *   *
 **********************************************/
 
class CheckCodeFile{
 
private $_codenum    = 4;        //验证码的位数
 
private $_codestr    = '';       //产生的验证码
 
private $_codeimg    = '';       //验证码图片
 
private $_codepix    = '';       //干扰素
 
private $_codewidth;             //验证码图片的宽度
 
private $_codeheight;            //验证码图片的高度
 
/**
* 构造函数
*/
public function __construct($w = 80,$h = 20){
session_start();
$this->_codewidth  = $w;
$this->_codeheight = $h;
}
/**
* 输出头部信息
* 输出为GIF的图片
*/
private function OutFileHeader(){
header("Content-type: image/png"); 
}//End OutFileHeader
/**
* 产生验证码字符
*/
private  function CreateCheckCodeStr(){
$this->_codestr = strtoupper(substr(md5(rand()),0,$this->_codenum));
//$_SESSION[code] = $this->_codestr;
return $this->_codestr;
}//End CreateCheckCode
/**
* 产生验证码图片
*/
private function CreateCheckCodeImg(){
$this->_codeimg = imagecreate($this->_codewidth,$this->_codeheight);
imagecolorallocate($this->_codeimg,200,200,200);
return $this->_codeimg;
}//End CreateCheckCodeImg
/**
* 设置验证图片的干扰素
*/
private function SetPixColor(){
for ($i=0;$i<128;$i++){
$this->_codepix = imagecolorallocate($this->_codeimg,rand(0,255),rand(0,255),rand(0,255));
imagesetpixel($this->_codeimg,rand(2,128),rand(2,38),$this->_codepix);
}
}//End SetPixColor
/**
* 在验证图片上画上验证码的字符
*/
private function WriteCheckCodeToImg(){
for ($i=0;$i<$this->_codenum;$i++){
$bgColor = imagecolorallocate($this->_codeimg,rand(0,255),rand(0,255),rand(0,255));
$x       = floor($this->_codewidth/$this->_codenum)*$i;
$y       = rand(0,$this->_codeheight-15);
imagechar($this->_codeimg,5,$x+10,$y,$this->_codestr[$i],$bgColor);
}
}//End WriteCheckCodeImg
/**
* 输出验证码图片
*/
public function OutChceckImage(){
$this->OutFileHeader();
$this->CreateCheckCodeStr();
$this->CreateCheckCodeImg();
$this->SetPixColor();
$this->WriteCheckCodeToImg();
imagepng($this->_codeimg);
imagedestroy($this->_codeimg);
}//End OutChceckImage
}//End Class
 
 
 
//例子
//$code = new CheckCodeFile(80,30);
//$code->OutChceckImage();
 
?>
原创粉丝点击