php生成验证码类代码

class securecode
{
    private static $instance=null;
    private $code = '';
    private $fontfile;
    private $validate;
    private $image;
    private $specialadd = 'special string for securecode';
    private $codeexpire=86400;
    private $codecookiename='secure_code';

    /**
     * 构造方法
     */
    private function securecode()
    {
        $this->fontfile = dirname( __file__ ) . '/arial.ttf';
    }

    private function __construct()
    {
        $this->securecode();
    }
   
    public static function getinstance()
    {
        if (self::$instance==null)
            self::$instance=new self();
       
        return self::$instance;
    }

    /**
     * 指定字体文件所在路径,默认为当前文件夹下arial.ttf文件
     * @param $fontfile 文件路径
     * @return void
     */
    function loadfont($fontfile)
    {
        $this->fontfile = $fontfile;
    }

    /**
     * 图片输出方法,在执行本方法前程序不应该有任何形式的输出
     * @return void;
     */
    function stroke()
    {
        $this->savecode();
        self::sendheader();
        imagegif( $this->validate );
        imagedestroy( $this->validate );
        imagedestroy( $this->image );
    }

    /**
     * 图片保存方法
     * @param $filename 保存路径
     * @return void
     */
    function save($filename)
    {
        $this->savecode();
        imagegif( $this->validate , $filename );
        imagedestroy( $this->validate );
        imagedestroy( $this->image );
    }
   
  /**
     * 验证码验证方法
     * @param $input 要验证的字符串,即用户的输入内容
     * @return boolean 验证结果
     */
    function verify($input)
    {
        $input=strtolower($input);
        $targetcode=$this->authcode($input);
        $code=$this->getcookie();
        if (empty($code)||$code!=$targetcode)
            $result= false;
        else
            $result=true;
        $_cookie[$this->codecookiename]='';
        setcookie ( $this->codecookiename, '', - 1 );
        return $result;
    }

    /**
     * 图片创建方法
     * @return void;
     */
    function createimage()
    {
        $this->randcode();
       
        $size = 30;
        $width = 90;
        $height = 35;
        $degrees = array (
            rand( 0 , 30 ), rand( 0 , 30 ), rand( 0 , 30 ), rand( 0 , 30 )
        );
       

        for ($i = 0; $i < 4; ++$i)
        {
            if (rand() % 2);
            else $degrees[$i] = -$degrees[$i];
        }
       
        $this->image = imagecreatetruecolor( $size , $size );
        $this->validate = imagecreatetruecolor( $width , $height );
        $back = imagecolorallocate( $this->image , 255 , 255 , 255 );
        $border = imagecolorallocate( $this->image , 0 , 0 , 0 );
        imagefilledrectangle( $this->validate , 0 , 0 , $width , $height , $back );
       
        for ($i = 0; $i < 4; ++$i)
        {
            $temp = self::rgbtohsv( rand( 0 , 250 ) , rand( 0 , 150 ) , rand( 0 , 250 ) );
           
            if ($temp[2] > 60) $temp[2] = 60;
           
            $temp = self::hsvtorgb( $temp[0] , $temp[1] , $temp[2] );
            $textcolor[$i] = imagecolorallocate( $this->image , $temp[0] , $temp[1] , $temp[2] );
        }
       
        for ($i = 0; $i < 200; ++$i)
        {
            $randpixelcolor = imagecolorallocate( $this->validate , rand( 0 , 255 ) , rand( 0 , 255 ) , rand( 0 , 255 ) );
            imagesetpixel( $this->validate , rand( 1 , 87 ) , rand( 1 , 35 ) , $randpixelcolor );
        }
       
        $temp = self::rgbtohsv( rand( 220 , 255 ) , rand( 220 , 255 ) , rand( 220 , 255 ) );
       
        if ($temp[2] < 200) $temp[2] = 255;
       
        $temp = self::hsvtorgb( $temp[0] , $temp[1] , $temp[2] );
        $randlinecolor = imagecolorallocate( $this->image , $temp[0] , $temp[1] , $temp[2] );
       
        self::imagelinethick( $this->validate , $textcolor[rand( 0 , 3 )] );
       
        imagefilledrectangle( $this->image , 0 , 0 , $size , $size , $back );
        putenv( 'gdfontpath=' . realpath( '.' ) );
       
        // name the font to be used (note the lack of the .ttf extension
        imagettftext( $this->image , 15 , 0 , 8 , 20 , $textcolor[0] , $this->fontfile , $this->code[0] );
       
        $this->image = imagerotate( $this->image , $degrees[0] , $back );
        imagecolortransparent( $this->image , $back );
        imagecopymerge( $this->validate , $this->image , 1 , 4 , 4 , 5 , imagesx( $this->image ) - 10 , imagesy( $this->image ) - 10 , 100 );
       
        $this->image = imagecreatetruecolor( $size , $size );
        imagefilledrectangle( $this->image , 0 , 0 , $size , $size , $back );
        imagettftext( $this->image , 15 , 0 , 8 , 20 , $textcolor[1] , $this->fontfile , $this->code[1] );
        $this->image = imagerotate( $this->image , $degrees[1] , $back );
        imagecolortransparent( $this->image , $back );
        imagecopymerge( $this->validate , $this->image , 21 , 4 , 4 , 5 , imagesx( $this->image ) - 10 , imagesy( $this->image ) - 10 , 100 );
       
        $this->image = imagecreatetruecolor( $size , $size );
        imagefilledrectangle( $this->image , 0 , 0 , $size - 1 , $size - 1 , $back );
        imagettftext( $this->image , 15 , 0 , 8 , 20 , $textcolor[2] , $this->fontfile , $this->code[2] );
        $this->image = imagerotate( $this->image , $degrees[2] , $back );
        imagecolortransparent( $this->image , $back );
        imagecopymerge( $this->validate , $this->image , 41 , 4 , 4 , 5 , imagesx( $this->image ) - 10 , imagesy( $this->image ) - 10 , 100 );
       
        $this->image = imagecreatetruecolor( $size , $size );
        imagefilledrectangle( $this->image , 0 , 0 , $size - 1 , $size - 1 , $back );
        imagettftext( $this->image , 15 , 0 , 8 , 20 , $textcolor[3] , $this->fontfile , $this->code[3] );
        $this->image = imagerotate( $this->image , $degrees[3] , $back );
        imagecolortransparent( $this->image , $back );
        imagecopymerge( $this->validate , $this->image , 61 , 4 , 4 , 5 , imagesx( $this->image ) - 10 , imagesy( $this->image ) - 10 , 100 );
        imagerectangle( $this->validate , 0 , 0 , $width - 1 , $height - 1 , $border );
    }
   
    /**
     * 获取随机生成的验证码
     * @return string 随机验证码,返回的验证码不进行任何处理
     */
    function getcode()
    {
        return $this->code;
    }

    /**
     * 生成随机码方法
     * @return void;
     */
    protected function randcode()
    {
        $alphastr = 'abcdefghijklmnpqrstuvwxyz123456789';
        $randstr = array (
            $alphastr{rand( 0 , 33 )}, $alphastr{rand( 0 , 33 )}, $alphastr{rand( 0 , 33 )}, $alphastr{rand( 0 , 33 )}
        );
        $this->code = strtolower( $randstr[0] . $randstr[1] . $randstr[2] . $randstr[3] );
    }

    /**
     * rgb色到hsv色转变方法
     * @param $r
     * @param $g
     * @param $b
     * @return array hsv数组
     */
    protected static function rgbtohsv($r, $g, $b)
    {
        $tmp = min( $r , $g );
        $min = min( $tmp , $b );
        $tmp = max( $r , $g );
        $max = max( $tmp , $b );
        $v = $max;
        $delta = $max - $min;
       
        if ($max != 0) $s = $delta / $max; // s
        else
        {
            $s = 0;
            //$h = undefinedcolor;
            return;
        }
        if ($r == $max) $h = ($g - $b) / $delta; // between yellow & magenta
        else if ($g == $max) $h = 2 + ($b - $r) / $delta; // between cyan & yellow
        else $h = 4 + ($r - $g) / $delta; // between magenta & cyan
       

        $h *= 60; // degrees
        if ($h < 0) $h += 360;
        return array (
            $h, $s, $v
        );
    }

    /**
     * 同上一方法功能相反
     * @param $h
     * @param $s
     * @param $v
     * @return array rgb数组
     */
    protected static function hsvtorgb($h, $s, $v)
    {
        if ($s == 0)
        {
            // achromatic (grey)
            $r = $g = $b = $v;
            return;
        }
       
        $h /= 60; // sector 0 to 5
        $i = floor( $h );
        $f = $h - $i; // factorial part of h
        $p = $v * (1 - $s);
        $q = $v * (1 - $s * $f);
        $t = $v * (1 - $s * (1 - $f));
       
        switch ($i)
        {
            case 0 :
                $r = $v;
                $g = $t;
                $b = $p;
                break;
            case 1 :
                $r = $q;
                $g = $v;
                $b = $p;
                break;
            case 2 :
                $r = $p;
                $g = $v;
                $b = $t;
                break;
            case 3 :
                $r = $p;
                $g = $q;
                $b = $v;
                break;
            case 4 :
                $r = $t;
                $g = $p;
                $b = $v;
                break;
            default : // case 5:
                $r = $v;
                $g = $p;
                $b = $q;
                break;
        }
        return array (
            $r, $g, $b
        );
    }

    /**
     * 使用cookie保存验证码的方法
     * @return void
     */
    protected function savecode()
    {
        $code = $this->authcode($this->code);
        $this->setcookie($code);
    }

    /**
     * 验证码cookie值获取方法
     * @return string cookie值
     */
    protected function getcookie()
    {
        if (empty( $_cookie[$this->codecookiename] ))
        {
            return '';
        }
        else
        {
            return addslashes($_cookie[$this->codecookiename]);
        }
    }
   
    /**
     * 验证码cookie创建方法
     * @param string $code 要保存的验证码
     * @return void
     */
    protected function setcookie($code)
    {
        $expire = $this->codeexpire > 0 ? $this->codeexpire + time() : 0;
        setcookie( $this->codecookiename , $code, $expire );
    }
   
    /**
     * 验证码加密方法
     * @param string $code 要加密的随机码
     * @return mixed 执行结果
     */
    protected function authcode($code)
    {
        return md5($code.$this->specialadd);
    }
   
    /**
     * 干扰线生成方法
     * @param resource $image 图片资源句柄
     * @param string $color 干扰线颜色
     */
    protected static function imagelinethick($image, $color)
    {
        $k = rand( 5 , 20 );
        for ($px = 0; $px < 400; $px = $px + 1)
        {
            $y = $k * sin( 0.1 * ($px) ); //$y=200+10*sin(0.1*($px-200));
            for ($i = 0; $i < 2; $i++)
            {
                imagesetpixel( $image , $px , $y + 10 + $i , $color );
            }
       
        }
    }

    /**
     * http标头设置方法
     * @return void
     */
    protected static function sendheader()
    {
        header( "pragma: no-cache" );
        header( "cache-control: max-age=1, s-maxage=1, no-cache, must-revalidate" );
        header( 'content-type: image/gif' );
    }
}
http://down.111cn.net/down/code/php/qitayuanma/2010/1220/22330.html

时间: 2024-09-27 08:34:43

php生成验证码类代码的相关文章

PHP 动态随机生成验证码类代码_php技巧

下面是效果图,这个效果图是没有开启干扰码的效果图 下面是类代码 复制代码 代码如下: <?php /************************************************ //FILE:ImageCode //DONE:生成动态验证码类 //DATE"2010-3-31 //Author:www.5dkx.com 5D开心博客 *********************************************************************

asp 生成验证码实例代码

asp教程 生成验证码实例代码 call com_creatvalidcode("validcode") sub com_creatvalidcode(ps教程n)     ' 禁止缓存   response.expires = -1   response.expiresabsolute = now() - 1    response.cachecontrol = "no-cache"      'response.expires = -9999      'res

PHP验证码类代码( 最新修改,完全定制化! )

Authnum.class.php 下载 复制代码 代码如下: <?php session_start(); class Authnum { //图片对象.宽度.高度.验证码长度 private $im; private $im_width; private $im_height; private $len; //随机字符串.y轴坐标值.随机颜色 private $randnum; private $y; private $randcolor; //背景色的红绿蓝,默认是浅灰色 public $

PHP验证码类代码( 最新修改,完全定制化! )_php技巧

Authnum.class.php 下载 复制代码 代码如下: <?php session_start(); class Authnum { //图片对象.宽度.高度.验证码长度 private $im; private $im_width; private $im_height; private $len; //随机字符串.y轴坐标值.随机颜色 private $randnum; private $y; private $randcolor; //背景色的红绿蓝,默认是浅灰色 public $

完美的php生成验证码程序代码

•新建一个PHP文件captcha_code_file.php  代码如下 复制代码 //首先开启session session_start(); //定义前台显示验证码长&宽 $image_width = 120; $image_height = 40; $characters_on_image = 6; $font = './monofont.ttf'; //The characters that can be used in the CAPTCHA code. //avoid confus

一个PHP验证码类代码分享(已封装成类)_php技巧

复制代码 代码如下: <?php session_start(); Header("Content-type: image/gif"); class SecurityCode { private $codes = ''; function __construct() { $code = '0-1-2-3-4-5-6-7-8-9-A-B-C-D-E-F-G-H-I-J-K-L-M-N-O-P-Q-R-S-T-U-V-W-X-Y-Z'; $codeArray = explode('-

实用PHP验证码类代码(1/2)

<?php教程 session_start(); class authnum { //图片对象.宽度.高度.验证码长度 private $im; private $im_width; private $im_height; private $len; //随机字符串.y轴坐标值.随机颜色 private $randnum; private $y; private $randcolor; //背景色的红绿蓝,默认是浅灰色 public $red=238; public $green=238; pu

一款php生成验证码实现代码

session_save_path,可重新定义目录. */ $sesssavepath = dirname(__file__)."/../data/sessions/"; if(is_writeable($sesssavepath) && is_readable($sesssavepath)){ session_save_path($sesssavepath); } session_start(); $vstr = ''; for($i=0; $i<4; $i++

asp 生成验证码程序代码

<% Option Explicit Response.buffer = True NumCode (8)   '注:1,4,7,10,13,16为彩色背景型 2,5,8,11,14,17为黑白型 3,6,9,12,15,18为噪点型 Function NumCode(CodeType)     Response.Expires = -1     Response.AddHeader "Pragma", "no-cache"     Response.AddH