2e2e2 发表于 2014-4-18 08:54:46

PHP验证码类


<?php

class verify{

    //随机因子
    private $text = 'abcdefghWddsdffgdWRFJKFJDFjjdfglkdfg883498Jhdsd9345345j340fg343o4j39d9t345j9dtej';

    //验证码句柄资源
    private $code;

    //验证码长度
    private $length = 4;

    //验证码字体大小
    private $size = 20;

    //生成图像的高度
    private $height = 30;

    //验证码字体
    private $font;

    //图像资源句柄
    private $image;

    /**
   *构造方法初始化
   */
    public function __construct(){
      $this->font = './static/fonts/msyh.ttf';
    }

    /**
   *生成随机码
   */
    private function createcode(){
      $textlength = strlen($this->text)-1;
      for($i=0; $i<$this->length; $i++){
            $this->code .= $this->text;
      }
    }

    /**
   *创建图像
   */
    private function createimg(){
      //创建画布
      $this->image = imagecreatetruecolor($this->size*$this->length, $this->height);

      //随机背景色
      $color = imagecolorallocate($this->image, rand(0,255), rand(100,255), 175);

      //创建矩形
      imagefilledrectangle($this->image, 0, $this->height, $this->size*$this->length, 0, $color);
    }

    /**
   *生成文字
   */

    private function createtext(){
      for($i=0;$i<$this->length;$i++){
            $color = imagecolorallocate($this->image, 255, 255, 255);
            imagettftext($this->image, $this->size, 0, 2, 25, $color, $this->font, $this->code);
      }

      //设置字符间距
      //imagepsbbox($this->text, $this->font, $this->size);
    }

    /**
   *生成干扰线 以及 $string字符
   */
    private function createline(){
      $string = '--';
      for($i=0; $i<1; $i++){
            $color = imagecolorallocate($this->image, rand(200,255), rand(200,255), rand(200,255));
            imageline($this->image, rand(1,$this->size*$this->length), rand(1,$this->height), rand(1,$this->size*$this->length), rand(1,$this->height), $color);
      }
      for($i=0; $i<10; $i++){
            $color = imagecolorallocate($this->image, rand(0,10), rand(50,150), rand(200,255));
            imagestring($this->image, 1, rand(0,$this->size*$this->length), rand(0,$this->height), $string, $color);
      }
    }

    /**
   *输出图像
   */
    private function outimage(){
      header('content-type:image/png');
      imagepng($this->image);
      imagedestroy($this->image);
    }

    /**
   *对外生成验证
   */
    public function doimage(){
      $this->createimg();
      $this->createcode();
      $this->createtext();
      $this->createline();
      $this->outimage();
    }

    //获取验证码
    public function getverify() {
      return strtolower($this->code);
    }

}

?>

页: [1]
查看完整版本: PHP验证码类