1. 程式人生 > >實現圖片驗證碼類 PHP

實現圖片驗證碼類 PHP

-type cli ont eat edi doc out text src

封裝一個圖片驗證碼類

<?php
class Captcha{
    private $img;
    private $imgX;
    private $imgY;
    private $codeNum;
    private $code;
    private $str="abcdefghjklmnpqrstuvwxyz123456789ABCDEFGHJKLMNPQRSTUVWXYZ";

    public function __construct($imgX=80,$imgY=40,$codeNum=4){
        $this->imgX=$imgX
; $this->imgY=$imgY; $this->codeNum=$codeNum; } public function printImg(){ $this->createBg(); $this->getCode(); $this->setCode(); $this->setDot(); $this->setCurve(); $this->outImg(); } //創建畫布背景圖片 private
function createBg(){ //創建畫布 $this->img=imagecreate($this->imgX,$this->imgY); //給圖片背景顏色分配 imagecolorallocate($this->img,243,251,254); } //輸出背景圖片 private function outImg(){ header("Content-type:image/jpeg"); imagejpeg($this->img); }
//生成驗證碼 private function getCode(){ //生成驗證碼 for($i=0;$i<$this->codeNum;$i++){ $key=rand(0,strlen($this->str)-1); $this->code.=$this->str[$key]; } $this->setSession(); } //生成背景圖片和文字顏色 private function setCode(){ for($i=0;$i<$this->codeNum;$i++){ $char_color=imagecolorallocate($this->img,rand(0,255),rand(0,255),rand(0,255)); $font_size=rand(3,5); $font_height=imagefontheight($font_size);//根據設置的字體大小獲取字體高度 $x=($this->imgX/$this->codeNum)*$i;//設置驗證碼每個字的坐標位置 $y=rand(0,$this->imgY-$font_height-3); imagechar($this->img,$font_size,$x,$y,$this->code{$i},$char_color);//把字符串寫到圖片上 imagechar() } } //畫幹擾點 private function setDot(){ for($i=0;$i<=50;$i++){ $dot_color=imagecolorallocate($this->img,rand(0,255),rand(0,255),rand(0,255)); imagesetpixel($this->img,rand(1,80),rand(1,40),$dot_color);//把幹擾點寫到圖片上 imagesetpixel() } } //畫幹擾線 private function setCurve(){ for($i=0;$i<=3;$i++){ $line_color=imagecolorallocate($this->img,rand(0,255),rand(0,255),rand(0,255)); imagearc($this->img,rand(1,$this->imgX),rand(1,$this->imgY),100,80,30,15,$line_color); } } //把驗證碼存儲到session private function setSession(){ session_start(); $_SESSION[‘code‘]=strtolower($this->code); } } $captcha=new Captcha; $captcha->printImg();

在外部調用類

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
  <title> new document </title>
  <meta name="generator" content="editplus" />
  <meta name="author" content="" />
  <meta name="keywords" content="" />
  <meta name="description" content="" />
  <meta charset="utf-8">
 </head>

 <body>

 <label>請輸入驗證碼:</label><input type="text"><img src="captcha.php" onclick="this.src=‘captcha.php?‘+Math.random()" />
 </body>
</html>

實現圖片驗證碼類 PHP