美しい php 検証コード クラス (共有)_PHP チュートリアル

WBOY
リリース: 2016-07-21 14:59:25
オリジナル
926 人が閲覧しました

コードを直接アップロードします:

コードをコピーします コードは次のとおりです:

//検証コードクラス
class ValidateCode {
private $charset = 'abcdefghkmnprstuvwxyzABCDEFGHKMNPRSTUVWXYZ23456789';//ランダム因子
プライベート $code ; //検証コード
private $codelen = 4;//検証コードの長さ
private $width = 130;//幅
private $height = 50;//高さ
private $img;//グラフィックリソースハンドル
private $font ;//フォント指定
private $fontsize = 20;//フォントサイズ指定
private $fontcolor;//フォントカラー指定
//コンストラクターメソッド初期化
public function __construct() {
$this->font = dirname( __FILE__).' /font/elephant.ttf';//フォントのパスを正しく書かないと画像が表示されないことに注意してください
}
//ランダムなコードを生成します
private function createCode() {
$_len = strlen($this->charset)- 1;
for ($i=0;$icodelen;$i++) {
$this->code .= $this->charset [mt_rand(0,$_len)];
}
}
//背景を生成
プライベート関数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 ->フォントサイズ,mt_rand(-30,30),$_x*$i+mt_rand(1,5),$this->高さ / 1.4,$this-> ;fontcolor,$this->font,$ this->code[$i]);
}
}
//線と雪の結晶を生成
private function createLine() {
//Line
for ($i= 0;$i $color = imagecolorallocate($this->img,mt_rand(0,156),mt_rand(0,156),mt_rand(0,156));
imageline($this->img, mt_rand(0,$this->幅)、mt_rand(0,$this->高さ)、mt_rand(0,$this->幅)、mt_rand(0,$this->高さ)、$color );
}
//スノーフレーク
for ( $i=0;$i $color = imagecolorallocate($this->img,mt_rand(200,255),mt_rand(200,255),mt_rand( 200,255));
画像文字列($this-> ;img,mt_rand(1,5),mt_rand(0,$this->幅),mt_rand(0,$this->高さ),'*',$ color);
}
}
//出力
プライベート関数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 strto lower($this->code);
}
}

出力例:

使用法:
1. まず、検証コード クラスを ValidateCode.class.php という名前のファイルとして保存します。

captcha という名前の新しいファイルを作成します。
コードをコピーします

コードは次のとおりです:session_start();require './ValidateCode.class.php'; //最初にクラスをインクルードし、実際の状況に応じて実際のパスを変更します。
$_vc = new ValidateCode(); //オブジェクトをインスタンス化します
$_vc->doimg();
$_SESSION['authnum_session'] = $_vc->getCode(); //検証コードを SESSION に保存します


3. ページへの参照、コードは次のとおりです:


コードをコピーします
コードは次のとおりです:

4. 完全な検証ページのコードは次のとおりです:
コードをコピーします コードは次のとおりです:

session_start();
// このページでは、次のことを行う必要があります。まずセッションを開きます。
//error_reporting( 2047);
session_destroy();
//毎回新しいセッション値を取得できるようにセッションを削除します。
//seesion を使用するとうまく機能し、非常に便利です
?> ;


セッション画像検証の例