国产精品成人VA在线观看,亚洲日韩在线中文字幕综合,亚洲AV电影天堂男人的天堂,久久人人爽人人爽人人av东京热

News新聞

業(yè)界新聞動(dòng)態(tài)、技術(shù)前沿
Who are we?

您的位置:首頁      樂道系統(tǒng)FAQ      PHP 用session與gd庫實(shí)現(xiàn)簡單驗(yàn)證碼生成與驗(yàn)證的類方法

PHP 用session與gd庫實(shí)現(xiàn)簡單驗(yàn)證碼生成與驗(yàn)證的類方法

標(biāo)簽: 發(fā)布日期:2016-11-15 00:00:00 292

驗(yàn)證碼是為了防止機(jī)器灌水給網(wǎng)站帶來污染以及增加服務(wù)器負(fù)擔(dān)而出現(xiàn)的。目前大大小小的網(wǎng)站都有驗(yàn)證碼。今天自己實(shí)現(xiàn)了一個(gè)簡單的驗(yàn)證碼類。說簡單是因?yàn)闆]有加一些干擾的弧線等等,只是將文字旋轉(zhuǎn)了一下。當(dāng)然,因?yàn)樽煮w的原因,要想一眼看出來并不容易。同時(shí),為了避免字母的大小寫與數(shù)字混淆,又去掉了那些看起來很像的字母數(shù)字。
類:

<?php
/**
 *簡單生成驗(yàn)證碼類
 */
class Captcha {
  private $width;//驗(yàn)證碼寬度
  private $height;//驗(yàn)證碼高度
  private $countOfChars;//字符數(shù)
  //private $distrubLines;//干擾線條數(shù)
  private $chars;//隨機(jī)生成的字符串

  public function __construct($width=100,$height=30,$countOfChars=4,$distrubLines=2) {
  //初始化參數(shù)
  $this->width=$width;
  $this->height=$height;
  $this->countOfChars=$countOfChars;
  session_start();
  }

  /**
   * 執(zhí)行全部動(dòng)作,生成驗(yàn)證碼并直接輸出
   */
  public function execute(){
  $imageHandle=$this->createImage();
  $this->createChars();
  $this->drawChars($imageHandle);
  $this->outImage($imageHandle);
  }

  /**
   * 創(chuàng)建畫布,并隨機(jī)填充顏色
   * @return 返回畫布句柄
   */
  public function createImage(){
  $imageHandle= imagecreate($this->width, $this->height);
  //隨機(jī)背景顏色
    $randColor=imagecolorallocate($imageHandle, 50, mt_rand(0, 50), mt_rand(0, 50));
  imagefill($imageHandle, 0, 0, $randColor);
  return $imageHandle;
  }

  /**
   * 生成隨機(jī)字符
   */
  private function createChars(){
  //候選字符
  $str='ABCDEFGHJKLMNPQRSTUVWXZabcdefghijkmnpqtuvwx2346789';
  $chars='';
  for($i=0;$i<$this->countOfChars;$i++){
    $chars.=$str[mt_rand(0,strlen($str)-1)];
  }
  $this->chars=$chars;
  //保存在會(huì)話中
  $_SESSION['captcha']=strtolower($chars);
  }

  /**
   * 將字符寫入圖像
   * @param type $imageHandle 圖像句柄
   */
  private function drawChars($imageHandle){
  if($this->chars!=null){
    $font='/home/WWW/YuWeiLiShuFT.ttf';
    for($i=0;$i<strlen($this->chars);$i++){
    $color= imagecolorallocate($imageHandle,mt_rand(50, 200),mt_rand(100, 255),255);
    imagefttext($imageHandle,30, 30,$i*20+10,25,$color,$font,$this->chars[$i]);
    }
  }
  }

  /**
   * 輸出圖像
   * @param type $imageHandle 圖像句柄
   */
  private function outImage($imageHandle){
  imagepng($imageHandle);
  imagedestroy($imageHandle);
  }

  /**
   * 判斷用戶輸入的驗(yàn)證碼是否正確
   * @param type $usrInput 用戶的輸入
   * @return boolean 驗(yàn)證碼是否匹配
   */
  public static function isRight($usrInput){
  if(isset($_SESSION['captcha'])){
    if(strtolower($usrInput)==$_SESSION['captcha']){
    $_SESSION['captcha']=null;
    return true;
    }else{
    $_SESSION['captcha']=null;
    return false;
    }
  }
  }
}