<?php
/**
* captcha plugin
*/
class Captcha
{
private $session_name = 'session_name',
$width = 0,
$height = 0;
/**
* Construct
* @param string $folder
* @param integer $width
* @param integer $height
*/
public function __construct( $session_name = 'captcha_word', $width = 145, $height = 20 )
{
$this->init( $session_name, $width, $height );
}
/**
* init
*/
public function init( $session_name, $width, $height )
{
$this->session_name = $session_name;
$this->width = $width;
$this->height = $height;
}
/**
* check captcha
* @param string $word
* @return bool
*/
public function check( $captcha )
{
return isset( $_SESSION[$this->session_name] ) && $this->_encrypts(strtoupper( $captcha )) === $_SESSION[$this->session_name];
}
/**
* make captcha image
* @param string $word 验证码
* @return mix
*/
public function generateImage( $word = NULL )
{
/*
* make captcha word
*/
$word = is_null( $word ) ? $this->generateWord() : $word;
/*
* captch word length
*/
$letters = strlen( $word );
/*
* create image
*/
$img = imagecreatetruecolor ( $this->width, $this->height );
// color
$bg_color = imagecolorallocate( $img , rand( 0, 128 ), rand( 0, 128 ), rand( 0, 128 ));
$txt_color = imagecolorallocate( $img , rand( 128, 256 ), rand( 128, 256 ), rand( 128, 256 ));
// background
imagefilledrectangle( $img, 0, 0, $this->width, $this->height, $bg_color );
// add point
for($i = 0; $i < 100; $i++)
{
$point_color = imagecolorallocate( $img, rand( 0, 256 ), rand( 0, 256 ), rand( 0, 256 ));
$rand_x = rand(0, $this->width);
$rand_y = rand(0, $this->height);
imageline( $img, $rand_x, $rand_y, $rand_x + 1, $rand_y + 1, $point_color );
}
// add letter
$x = ($this->width - (imagefontwidth(5) * $letters)) / 2;
$y = ($this->height - imagefontheight(5)) / 2;
imagestring($img, 5, $x, $y, $word, $txt_color);
// print image
header('Expires: Thu, 01 Jan 1970 00:00:00 GMT');
// HTTP/1.1
header('Cache-Control: private, no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0, max-age=0', false);
// HTTP/1.0
header('Pragma: no-cache');
header('Content-type: image/jpeg');
imagejpeg($img);
imagedestroy($img);
}
/**
* encrypts captha
* @param string $word
* @return string
*/
private function _encrypts( $word )
{
return md5( $word );
}
/**
* make catpcha
* @access private
* @param integer $length
* @return string
*/
private function generateWord( $length = 4 )
{
/*
* make word
*/
$chars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
$word = substr(str_shuffle( $chars ), 0, $length );
/*
* session
*/
$_SESSION[$this->session_name] = $this->_encrypts( $word );
/*
* return
*/
return $word;
}
}
?>
使用
//生成验证码图片
$cap = new Captcha();
$cap->generateImage();
//验证
$cap = new Captcha();
$cap->check($_POST['captcha']);