PHP常用类

PHP常用类

一、分页类

<?php
/**
 * 分页类
 * 调用方式:
 * $p=new Page(总条数,显示页码链接数量,当前页码,每页显示条数,[链接]);
 * print_r($p->getPages()); //生成一个页码数组(键为页码,值为链接)
 * echo $p->showPages(1);    //生成一个页码样式(可添加自定义样式),1为默认样式
 *
 */
class Page{
    protected $count;       //总记录条数
    protected $showPages;   //标签中需要显示的页码链接数量
    protected $countPages;  //总记录页数
    public $currPage;    //当前页
    public $subPages;    //每页显示记录条数
    protected $href;        //连接
    protected $page_arr=array();    //保存生成的页码 键为页码 值为连接

    /**
     * __construct  构造函数(获取分页所需参数)
     * @param int $count     总记录条数
     * @param int $showPages 显示页码链接数量
     * @param int $currPage  当前页数
     * @param int $subPages  每页显示记录数量
     * @param string $href   连接(不设置则获取当前URL)
     */
    public function __construct($count,$showPages,$currPage,$subPages,$href=''){
        $this->count=$count;
        $this->showPages=$showPages;
        $this->currPage=$currPage;
        $this->subPages=$subPages;

        //如果链接没有设置则获取当前连接
        if(empty($href)){
            //htmlentities() 函数把字符转换为 HTML 实体。
            $this->href=htmlentities($_SERVER['PHP_SELF']);
        }else{
            $this->href=$href;
        }
        //生成页码数组方法
        $this->construct_Pages();
    }

    /**
     * getPages 返回页码数组
     * @return array 一维数组 键为页码 值为链接
     */
    public function getPages(){
        return $this->page_arr;
    }

    /**
     * showPages 返回生成好的页码
     * @param  int $style 样式
     * @return string     生成好的页码
     */
    public function showPages($style=1){
        $func='pageStyle'.$style;
        return $this->$func();
    }

    /**
     * pageStyle1 分页样式(可参照这个添加自定义样式 例如pageStyle2())
     * 样式 共45条记录,每页显示10条,当前第1/5页 [首页] [上页] [1] [2] [3] .. [下页] [尾页]
     * @return string
     */
    protected function pageStyle1(){
        /* 构造普通模式的分页
        共4523条记录,每页显示10条,当前第1/453页 [首页] [上页] [1] [2] [3] .. [下页] [尾页]
        */
        $pageStr='共'.$this->count.'条记录,每页显示'.$this->subPages.'条';
        $pageStr.='当前第'.$this->currPage.'/'.$this->countPages.'页 ';
        //设置首页链接
        $_GET['page'] = 1;
        $pageStr.='<span>[<a href="'.$this->href.'?'.http_build_query($_GET).'">首页</a>] </span>';

        //如果当前页不是第一页就显示上页链接按钮
        if($this->currPage>1){
            $_GET['page'] = $this->currPage-1;
            $pageStr.='<span>[<a href="'.$this->href.'?'.http_build_query($_GET).'">上页</a>] </span>';
        }

        //生成页码链接
        foreach ($this->page_arr as $k => $v) {
            $_GET['page'] = $k;
            if($k==$this->currPage){
                $pageStr.='<span>[<a style="background-color: red;" href="'.$v.'">'.$k.'</a>] </span>';
                continue;
            }
            $pageStr.='<span>[<a href="'.$v.'">'.$k.'</a>] </span>';
        }

        //如果当前页小于总页数就显示下一页链接按钮
        if($this->currPage<$this->countPages){
            $_GET['page'] = $this->currPage+1;
            $pageStr.='<span>[<a href="'.$this->href.'?'.http_build_query($_GET).'">下页</a>] </span>';
        }
        //设置尾页链接
        $_GET['page'] = $this->countPages;
        $pageStr.='<span>[<a href="'.$this->href.'?'.http_build_query($_GET).'">尾页</a>] </span>';
        //返回分页样式
        return $pageStr;
    }

    /**
     * construct_Pages 生成页码数组
     * 键为页码,值为链接
     * $this->page_arr=Array(
     *                  [1] => index.php?page=1
     *                  [2] => index.php?page=2
     *                  [3] => index.php?page=3
     *                  ......)
     */
    protected function construct_Pages(){
        //计算总页数
        $this->countPages=ceil($this->count/$this->subPages);
        //左边需要显示标签页码链接数量,当前页在中间显示
        $leftPage_num=floor($this->showPages/2);
        //$rightPage_num=$this->showPages-$leftPage_num;

        //左边显示数为当前页减左边该显示的数 例如总显示页码链接数量为7 当前页是5  左边最小为5-3  右边为2+7-1
        $left=$this->currPage-$leftPage_num;//求最左边的页码
        $left=max($left,1); //左边最小不能小于1
        $right=$left+$this->showPages-1; //左边加显示总页码数减1就是右边显示数
        $right=min($right,$this->countPages);  //右边最大不能大于总页数
        $left=max($right-$this->showPages+1,1); //确定右边再计算左边,必须二次计算
        //根据页码生成链接数组,键为页码,值为连接
        for ($i=$left; $i <= $right; $i++) {
            $_GET['page'] = $i;
            //使用给出的关联(或下标)数组生成一个经过 URL-encode 的请求字符串。
            $this->page_arr[$i]=$this->href.'?'.http_build_query($_GET);
        }
    }
}

?>

二、PDO类

<?php
/**
 * PDO MySQL类
 * Class MySQLPDO
 */
class MySQLPDO
{
    //保存PDO实例
    protected static $db = null;

    public function __construct()
    {
        self::$db || self::connect();
    }

    /**
     * 连接MySQL
     */
    protected function connect()
    {
        $dsn = 'mysql:host=localhost;dbname=news';
        self::$db = new PDO($dsn,'root','root',[PDO::ATTR_PERSISTENT => true]);
        self::$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
        self::$db->query('set names utf8');
    }

    /**
     * 通过预处理方式执行SQL
     * @param string $sql 执行的SQL语句模板
     * @param array $data 数据部分 可能是多维
     * @return object PDOStatement
     */
    public function query($sql, array $data=[])
    {
        $stmt = self::$db->prepare($sql);
        #考虑批量操作情况
        is_array(current($data)) || $data = [$data];
        foreach ($data as $arr){
            if($stmt->execute($arr) === false ){
                throw new PDOException('数据库操作失败:'.implode('-',$stmt->errorInfo())."\nSQL语句:".$sql);
            }
        }
        return $stmt;
    }


    /**
     * 执行SQL-写操作(支持批量操作,返回受影响的行数)
     * @param $sql
     * @param array $data
     * @return mixed
     */
    public function exec($sql, $data=[])
    {
        return $this->query($sql, $data)->rowCount();
    }

    /**
     * 取得一行结果(关联数组)
     * @param $sql
     * @param array $data
     * @return mixed
     */
    public function fetchRow($sql, $data=[])
    {
        return $this->query($sql, $data)->fetch(PDO::FETCH_ASSOC);
    }

    /**
     * 取得所有结果(关联数组)
     * @param $sql
     * @param array $data
     * @return mixed
     */
    public function fetchAll($sql, $data=[])
    {
        return $this->query($sql, $data)->fetchAll(PDO::FETCH_ASSOC);
    }

    /**
     * 取得一列结果
     * @param $sql
     * @param array $data
     * @return mixed
     */
    public function fetchColumn($sql, $data=[])
    {
        return $this->query($sql, $data)->fetchColumn();
    }

    /**
     * 最后插入的ID
     * @return mixed
     */
    public function lastInsertId()
    {
        return self::$db->lastInsertId();
    }

    /**
     * 事务处理-启动
     * @return mixed
     */
    public function startTrans()
    {
        return self::$db->beginTransaction();
    }

    /**
     * 事务处理-提交
     * @return mixed
     */
    public function commit()
    {
        return self::$db->commit();
    }


    /**
     * 事务处理-回滚
     * @return mixed
     */
    public function rollBack()
    {
        return self::$db->rollBack();
    }
}
?>
<?php
/**
 * 数据表模型基类
 *  get_called_class  (实例的谁)  和 __CLASS__ (在哪个类里面) 区别
 *  static   self
 * User: Jack<376927050@qq.com>
 * Date: 2018/10/23
 * Time: 16:53
 */
namespace framework;

class Model
{
    // 数据表名
    protected $tableName;
    // 数据表字段
    protected $primaryKey;
    // 条件
    protected $conditionBox = [
        'field' => '*',
        'where' => '',
        'order' => '',
        'limit' => ''
    ];
    protected $data = [];
    /**
     * 初始化工作
     * Model constructor.
     */
    public function __construct()
    {
        # 获取表名
        $arrTemp = explode('\\',get_called_class());
        var_dump($arrTemp);
        $this->tableName = $arrTemp[count($arrTemp)-1];
        # 获取表的主键
        $this->primaryKey = $this->getTablePriamryKey();
    }

    public function where($field,$symbol,$value = '')
    {
        if( empty($value) ){
            $value = $symbol;
            $symbol = '=';
        }
        $where = [];
        switch ($symbol)
        {
            case '=':
                $where = ["`$field` = :$field",[":$field"=>$value]];
                break;
            case '>':
                $where = ["`$field` > :$field",[":$field"=>$value]];
                break;
            case '<':
                $where = ["`$field` < :$field",[":$field"=>$value]];
                break;
            case 'like':
                $where = ["`$field` like :$field",[":$field"=>$value]];
                break;
            case 'in':
                if( is_array($value) ){
                    $value = implode(",",$value);
                }
                $where = ["`$field` in ($value)",[]];
                break;
        }
        if( !empty($where[0]) ){
            $this->data = array_merge($this->data,$where[1]);
            $condition = $where[0];
            $this->conditionBox['where'] = " where $condition";
        }
        return $this;
    }

    public function field($fields)
    {
        if( is_array($fields) ){
            $fields = implode(',',$fields);
        }
        $this->conditionBox['field'] = $fields;
        return $this;
    }

    public function order($cond)
    {
        $this->conditionBox['order'] = " order by $cond";
        return $this;
    }

    public function limit($condition)
    {
        $this->conditionBox['limit'] = " limit $condition";
        return $this;
    }

    public function find(int $pkId)
    {
        $sql = "select * from {$this->tableName} where {$this->primaryKey}=:{$this->primaryKey}";
        return (new MySQLPDO())->fetchRow($sql,[":{$this->primaryKey}"=>$pkId]);
    }
    /**
     * 根据条件获取查询记录
     * @return array
     */
    public function select()
    {
        $sql = sprintf('select %s from %s%s%s%s',
            $this->conditionBox['field'],
            $this->tableName,
            $this->conditionBox['where'],
            $this->conditionBox['order'],
            $this->conditionBox['limit']
        );
        return (new MySQLPDO())->fetchAll($sql,$this->data);
    }
    /**
     * 添加数据
     * @param $data
     * @return int | bool
     */
    public function insert(array $data){
        //获取所有字段
        $fields = array_keys($data);
        //拼接SQL语句
        $sql = "INSERT INTO `{$this->tableName}` (`".implode('`,`', $fields).'`) VALUES (:'.implode(',:', $fields).')';
        //调用数据库操作类执行SQL,成功返回最后插入的ID,失败返回false
        $mysql_pdo = new MySQLPDO();
        return $mysql_pdo->query($sql, $data) ? $mysql_pdo->lastInsertId() : false;
    }
    /**
     * 更新数据
     * @param array $data
     * @return bool|mixed
     */
    public function update(array $data){
        //获取所有字段
        $fields = array_keys($data);
        $handelBindParams = array_map(function($v){
            return "`$v`=:$v";
        },$fields);
        $update_fields = implode(',', $handelBindParams);
        $format = "UPDATE %s SET %s %s";
        $sql = sprintf($format,$this->tableName,$update_fields,$this->conditionBox['where']);
        return (new MySQLPDO())->exec($sql, $data);
    }
    /**
     * 统计总记录数
     * @return mixed
     */
    public function count()
    {
        $format = "SELECT * FROM %s %s";
        $sql = sprintf($format,
            $this->tableName,
            $this->conditionBox['where']
        );
        return (new MySQLPDO())->exec($sql);
    }

    public function paginate(int $limit = 1)
    {
        $total = $this->count();
        $pager = new \framework\libs\Page($total,$limit);
        $condition = $pager->getDbFetchCondition();
        $list = $this->limit($condition)->select();
        return ['data'=>$list,'html'=>$pager->showPage()];
    }
    /**
     * 获取表的主键
     */
    protected function getTablePriamryKey()
    {
        $dbname = config('db.dbname');
        $sql = "SELECT * FROM information_schema.`COLUMNS` WHERE table_name='{$this->tableName}' AND table_schema = '{$dbname}'";
        $result = (new MySQLPDO())->fetchAll($sql);
        foreach ($result as $rows){
            if( $rows['COLUMN_KEY'] == 'PRI' ){
                return $rows['COLUMN_NAME'];
            }
        }
    }
}

三、DB类

<?php
// 数据库连接类
class DB{
    //私有的属性
    private static $dbcon=false;
    private $host;
    private $port;
    private $user;
    private $pass;
    private $db;
    private $charset;
    private $link;
    //私有的构造方法
    public function __construct(){
        $this->host =  'localhost';
        $this->port =  '3306';
        $this->user =  'root';
        $this->pass =  'root';
        $this->db =  'robot';
        $this->charset= 'utf8';
        //连接数据库
        $this->db_connect();
        //选择数据库
        $this->db_usedb();
        //设置字符集
        $this->db_charset();
    }
    //连接数据库
    private function db_connect(){
        $this->link=mysqli_connect($this->host.':'.$this->port,$this->user,$this->pass);
        if(!$this->link){
            echo "数据库连接失败<br>";
            echo "错误编码".mysqli_errno($this->link)."<br>";
            echo "错误信息".mysqli_error($this->link)."<br>";
            exit;
        }
    }
    //设置字符集
    private function db_charset(){
        mysqli_query($this->link,"set names {$this->charset}");
    }
    //选择数据库
    private function db_usedb(){
        mysqli_query($this->link,"use {$this->db}");
    }
    //执行sql语句的方法
    public function query($sql){
        $res=mysqli_query($this->link,$sql);
        if(!$res){
            echo "sql语句执行失败<br>";
            echo "错误编码是".mysqli_errno($this->link)."<br>";
            echo "错误信息是".mysqli_error($this->link)."<br>";
        }
        return $res;
    }
    //获得最后一条记录id
    public function getInsertid(){
        return mysqli_insert_id($this->link);
    }
    /**
     * 查询某个字段
     * @param
     * @return string or int
     */
    public function getOne($sql){
        $query=$this->query($sql);
        return mysqli_free_result($query);
    }
    //获取一行记录,return array 一维数组
    public function getRow($sql,$type="assoc"){
        $query=$this->query($sql);
        if(!in_array($type,array("assoc",'array',"row"))){
            die("mysqli_query error");
        }
        $funcname="mysqli_fetch_".$type;
        return $funcname($query);
    }
    //获取一条记录,前置条件通过资源获取一条记录
    public function getFormSource($query,$type="assoc"){
        if(!in_array($type,array("assoc","array","row")))
        {
            die("mysqli_query error");
        }
        $funcname="mysqli_fetch_".$type;
        return $funcname($query);
    }
    //获取多条数据,二维数组
    public function getAll($sql){
        $query=$this->query($sql);
        $list=array();
        while ($r=$this->getFormSource($query)) {
            $list[]=$r;
        }
        return $list;
    }

    public function selectAll($table,$where,$fields='*',$order='',$skip=0,$limit=1000)
    {
        if(is_array($where)){
            foreach ($where as $key => $val) {
                if (is_numeric($val)) {
                    $condition = $key.'='.$val;
                }else{
                    $condition = $key.'=\"'.$val.'\"';
                }
            }
        } else {
            $condition = $where;
        }
        if (!empty($order)) {
            $order = " order by ".$order;
        }
        $sql = "select $fields from $table where $condition $order limit $skip,$limit";
        $query = $this->query($sql);
        $list = array();
        while ($r= $this->getFormSource($query)) {
            $list[] = $r;
        }
        return $list;
    }
    /**
     * 定义添加数据的方法
     * @param string $table 表名
     * @param string orarray $data [数据]
     * @return int 最新添加的id
     */
    public function insert($table,$data){
        //遍历数组,得到每一个字段和字段的值
        $key_str='';
        $v_str='';
        foreach($data as $key=>$v){
            //  if(empty($v)){
            //   die("error");
            // }
            //$key的值是每一个字段s一个字段所对应的值
            $key_str.=$key.',';
            $v_str.="'$v',";
        }
        $key_str=trim($key_str,',');
        $v_str=trim($v_str,',');
        //判断数据是否为空
        $sql="insert into $table ($key_str) values ($v_str)";
        $this->query($sql);
        //返回上一次增加操做产生ID值
        return $this->getInsertid();
    }
    /*
     * 删除一条数据方法
     * @param1 $table, $where=array('id'=>'1') 表名 条件
     * @return 受影响的行数
     */
    public function deleteOne($table, $where){
        if(is_array($where)){
            foreach ($where as $key => $val) {
                $condition = $key.'='.$val;
            }
        } else {
            $condition = $where;
        }
        $sql = "delete from $table where $condition";
        $this->query($sql);
        //返回受影响的行数
        return mysqli_affected_rows($this->link);
    }
    /*
    * 删除多条数据方法
    * @param1 $table, $where 表名 条件
    * @return 受影响的行数
    */
    public function deleteAll($table, $where){
        if(is_array($where)){
            foreach ($where as $key => $val) {
                if(is_array($val)){
                    $condition = $key.' in ('.implode(',', $val) .')';
                } else {
                    $condition = $key. '=' .$val;
                }
            }
        } else {
            $condition = $where;
        }
        $sql = "delete from $table where $condition";
        $this->query($sql);
        //返回受影响的行数
        return mysqli_affected_rows($this->link);
    }
    /**
     * [修改操作description]
     * @param [type] $table [表名]
     * @param [type] $data [数据]
     * @param [type] $where [条件]
     * @return [type]
     */
    public function update($table,$data,$where,$limit=0){
        //遍历数组,得到每一个字段和字段的值
        $str='';
        foreach($data as $key=>$v){
            $str.="$key='$v',";
        }
        $str=rtrim($str,',');
        if(is_array($where)){
            foreach ($where as $key => $val) {
                if(is_array($val)){
                    $condition = $key.' in ('.implode(',', $val) .')';
                } else {
                    $condition = $key. '=' .$val;
                }
            }
        } else {
            $condition = $where;
        }

        if (!empty($limit)) {
            $limit = " limit ".$limit;
        }else{
            $limit='';
        }
        //修改SQL语句
        $sql="update $table set $str where $condition $limit";
        $this->query($sql);
        //返回受影响的行数
        return mysqli_affected_rows($this->link);
    }
}
?>

<?php
//链式操作
class Db
{
  protected $link;
  protected $config=[
  'DB_HOST'=>'localhost',
  'DB_USER'=>'root',
  'DB_PASS'=>'root',
  'DB_NAME'=>'v1'
  ];
  protected $sql;
  // 数据库表名
  protected $table;

  // 条件
  protected $conditionBox = [
  'field' => '*',
  'where' => '',
  'order' => '',
  'limit' => ''
  ];
  protected $data = [];

  public function __construct()
 {  self::connect();
  }
  /**
 * 连接MySQL */  protected function connect()
 {  $link =mysqli_connect($this->config['DB_HOST'],$this->config['DB_USER'],$this->config['DB_PASS'],$this->config['DB_NAME']);
  if(!$link){
  exit('连接数据库失败!');
  }
  if(!mysqli_set_charset($link,'utf8')){
  exit("设置字符集失败!");
  }
  $this->link=$link;
  }
  //执行sql语句
  public function query($sql){
  $res=mysqli_query($this->link,$sql);
  if(!$res){
  echo "sql语句执行失败<br>";
  echo "错误编码是".mysqli_errno($this->link)."<br>";
  echo "错误信息是".mysqli_error($this->link)."<br>";
  }
  return $res;
  }
  public function __get($name)
 {  return $name=='sql'?$this->sql:'false';
  }

  /**
 * @param $field 字段名
 * @return $this
 */  public function max($field)
 {  $this->conditionBox['field']=" max('".$field."')";
  return $this->select();
  }

  /**
 * @param $table 获得表名
 * @return $this
 */  public function table($table)
 {  $this->table=$table;
  return $this;
  }

  public function where($data)
 {  if( !empty($data) ){
  $this->conditionBox['where']=" where $data" ;
  }
  return $this;
  }

  public function field($fields)
 {  if( is_array($fields) ){
  $fields = implode(',',$fields);
  }
  $this->conditionBox['field'] = $fields;
  return $this;
  }

  public function order($cond)
 {  $this->conditionBox['order'] = " order by $cond";
  return $this;
  }

  public function limit($condition)
 {  $this->conditionBox['limit'] = " limit $condition";
  return $this;
  }

  /**
 * 根据条件获取查询记录 * @return array
 */  public function select()
 {  $sql = sprintf('select %s from `%s`%s%s%s',
  $this->conditionBox['field'],
  $this->table,
  $this->conditionBox['where'],
  $this->conditionBox['order'],
  $this->conditionBox['limit']
 );
  $arr=mysqli_fetch_all($this->query($sql),MYSQLI_ASSOC);
  return $arr;
  }
  /**
 * 添加数据 * @param $data 示例$data = ['name'=>'jack','age'=>18,'money'=>3000];
 * @return int | bool
 */  public function insert(array $data){
  $inserts=array_keys($data);
  $insert=implode(',',$inserts);
  $values=array_values($data);
  $value=implode("','",$values);
  $format = "insert into %s(%s) values('%s')";
  $sql = sprintf($format,$this->table,$insert,$value);
  $this->query($sql);
  return mysqli_affected_rows($this->link);
  }

  /**
 * 更新数据 * @param array $data  示例:$data = ['name'=>'jack','money'=>3000];
 * @return bool|mixed
 */  public function update(array $data){
  $update='';
  foreach($data as $k=>$v){
  $update.=$k."='".$v."',";
  }
  $update=rtrim($update,",");
  $format = "UPDATE %s SET %s %s";
  $sql = sprintf($format,$this->table,$update,$this->conditionBox['where']);
  $this->query($sql);
  return mysqli_affected_rows($this->link);
  }

  public function delete(){
  $sql = "delete from $this->table" .$this->conditionBox['where'];
  $this->query($sql);
  return mysqli_affected_rows($this->link);
  }

}

四、验证码类

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/7/24 0024
 * Time: 下午 4:49
 */

//验证码类
class ValidateCode {
    private $charset = 'abcdefghkmnprstuvwxyzABCDEFGHKMNPRSTUVWXYZ23456789';//随机因子
    private $code;//验证码
    private $codelen ;//验证码长度
    private $width;//宽度
    private $height;//高度
    private $img;//图形资源句柄
    private $font;//指定的字体格式
    private $fontsize;//指定字体大小
    private $fontcolor;//指定字体颜色
    //构造方法初始化
    public function __construct($codelen=4,$width=130,$height=50,$fontsize=20) {
        //dirname()返回路径中的目录部分,__FILE__ 文件的完整路径和文件名
        $this->codelen=$codelen;
        $this->width=$width;
        $this->height=$height;
        $this->fontsize=$fontsize;
        $this->font = dirname(__FILE__).'/simhei.ttf';//注意字体路径要写对,否则显示不了图片
    }
    //生成随机码
    private function createCode() {
        $_len = strlen($this->charset)-1;
        for ($i=0;$i<$this->codelen;$i++) {
            $this->code .= $this->charset[mt_rand(0,$_len)];
        }
    }
    //生成背景
    private function createBg() {
        //新建一个真彩色图像
        $this->img = imagecreatetruecolor($this->width, $this->height);
        //为一幅图像分配颜色
        $color = imagecolorallocate($this->img, mt_rand(157,255), mt_rand(157,255), mt_rand(157,255));
        //画一矩形并填充
        imagefilledrectangle($this->img,0,$this->height,$this->width,0,$color);
    }

    //生成文字
    private function createFont() {
        $_x = $this->width / $this->codelen;
        for ($i=0;$i<$this->codelen;$i++) {
            $this->fontcolor = imagecolorallocate($this->img,mt_rand(0,156),mt_rand(0,156),mt_rand(0,156));
            imagettftext($this->img,$this->fontsize,mt_rand(-20,20),$_x*$i+mt_rand(10,20),mt_rand($this->fontsize+5,$this->height-5),$this->fontcolor,$this->font,$this->code[$i]);
        }
    }
    //生成线条、雪花
    private function createLine() {
        //线条
        for ($i=0;$i<6;$i++) {
            $color = imagecolorallocate($this->img,mt_rand(0,156),mt_rand(0,156),mt_rand(0,156));
            imageline($this->img,mt_rand(0,$this->width),mt_rand(0,$this->height),mt_rand(0,$this->width),mt_rand(0,$this->height),$color);
        }
        //雪花
        for ($i=0;$i<100;$i++) {
            $color = imagecolorallocate($this->img,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255));
            imagestring($this->img,mt_rand(1,5),mt_rand(0,$this->width),mt_rand(0,$this->height),'*',$color);
        }
    }
    //输出
    private function outPut() {
        header('Content-type:image/png');
        imagepng($this->img);
        imagedestroy($this->img);
    }
    //对外生成
    public function doimg() {
        $this->createBg();
        $this->createCode();
        $this->createLine();
        $this->createFont();
        $this->outPut();
    }
    //获取验证码
    public function getCode() {
        return strtolower($this->code);
    }
}

/*$p=new ValidateCode(5,250,60,30);
$p->doimg();*/

posted @ 2021-09-05 19:50  成文的博客  阅读(57)  评论(0编辑  收藏  举报