本文實例講述了php實現的驗證碼文件類。分享給大家供大家參考。具體如下:
<?php /** * @file * @version 1.0 * @author 網海浪子 * @brief 驗證碼文件類 * */ class CCheckCodeFile { //驗證碼位數 private $mCheckCodeNum = 4; //產生的驗證碼 private $mCheckCode = ''; //驗證碼的圖片 private $mCheckImage = ''; //干擾像素 private $mDisturbColor = ''; //驗證碼的圖片寬度 private $mCheckImageWidth = '80'; //驗證碼的圖片寬度 private $mCheckImageHeight = '20'; /** * * @brief 輸出頭 * */ private function OutFileHeader() { header ("Content-type: image/png"); } /** * * @brief 產生驗證碼 * */ private function CreateCheckCode() { $this->mCheckCode = strtoupper(substr(md5(rand()),0,$this->mCheckCodeNum)); return $this->mCheckCode; } /** * * @brief 產生驗證碼圖片 * */ private function CreateImage() { $this->mCheckImage = @imagecreate ($this->mCheckImageWidth,$this->mCheckImageHeight); imagecolorallocate ($this->mCheckImage, 200, 200, 200); return $this->mCheckImage; } /** * * @brief 設置圖片的干擾像素 * */ private function SetDisturbColor() { for ($i=0;$i<=128;$i++) { $this->mDisturbColor = imagecolorallocate ($this->mCheckImage, rand(0,255), rand(0,255), rand(0,255)); imagesetpixel($this->mCheckImage,rand(2,128),rand(2,38),$this->mDisturbColor); } } /** * * @brief 設置驗證碼圖片的大小 * * @param $width 寬 * * @param $height 高 * */ public function SetCheckImageWH($width,$height) { if($width==''||$height=='')return false; $this->mCheckImageWidth = $width; $this->mCheckImageHeight = $height; return true; } /** * * @brief 在驗證碼圖片上逐個畫上驗證碼 * */ private function WriteCheckCodeToImage() { for ($i=0;$i<=$this->mCheckCodeNum;$i++) { $bg_color = imagecolorallocate ($this->mCheckImage, rand(0,255), rand(0,128), rand(0,255)); $x = floor($this->mCheckImageWidth/$this->mCheckCodeNum)*$i; $y = rand(0,$this->mCheckImageHeight-15); imagechar ($this->mCheckImage, 5, $x, $y, $this->mCheckCode[$i], $bg_color); } } /** * * @brief 輸出驗證碼圖片 * */ public function OutCheckImage() { $this ->OutFileHeader(); $this ->CreateCheckCode(); $this ->CreateImage(); $this ->SetDisturbColor(); $this ->WriteCheckCodeToImage(); imagepng($this->mCheckImage); imagedestroy($this->mCheckImage); } } $c_check_code_image = new CCheckCodeFile(); //$c_check_code_image ->SetCheckImageWH(100,50); //設置顯示驗證碼圖片的尺寸 $c_check_code_image ->OutCheckImage(); ?>
希望本文所述對大家的php程序設計有所幫助。