php验证码类
<?php
class ctl_admin_captcha extends ssc_controler{
public function index()
{
//加载验证码类并设置session
$captcha=$this->load->library('validatecode');
$captcha->gencodeimage();
$_SESSION['captcha'] = $captcha->getCode();
}
}
/*
* 验证码的类,需要加载字体文件
*
* */
class ssc_validatecode
{
private $charset = "abcdefghkmnprstuvwxyzABCDEFGHKMNPRSTUVWXYZ3456789";
private $code;
private $codelen = 4;
private $width = 150;
private $height = 50;
private $img;
private $font;
private $fontsize = 18;
private $fontcolor;
public function __construct()
{
if (!function_exists("imagecreatetruecolor") || !function_exists("imagecolorallocate") || !function_exists("imagefilledrectangle") || !function_exists("imagettftext") || !function_exists("imageline") || !function_exists("imagestring")) {
return false;
}
$this->font ="/LATINWD.TTF";
if (!file_exists($this->font)) {
return false;
}
}
public function __destruct()
{
if (isset($this->img)) {
unset($this->img);
$this->img = NULL;
}
if (isset($this->font)) {
unset($this->font);
$this->font = NULL;
}
}
private function createCode()
{
$_len = strlen($this->charset) - 1;
for ($i = 0; $i < $this->codelen; $i++) {
$this->code .= $this->charset[mt_rand(0, $_len)];
}
}
private function createBg()
{
$this->img = imagecreatetruecolor($this->width, $this->height);
$color = imagecolorallocate($this->img, 255, 255, 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, 0, 0, 0);
imagettftext($this->img, $this->fontsize, mt_rand(-25, 25), ($_x * $i) + mt_rand(1, 3), $this->height / 1.4, $this->fontcolor, $this->font, strtoupper($this->code[$i]));
}
}
private function createLine()
{
for ($i = 0; $i < 10; $i++) {
$color = imagecolorallocate($this->img, 0, 0, 0);
imageline($this->img, mt_rand(0, $this->width), mt_rand(0, $this->height), mt_rand(0, $this->width), mt_rand(0, $this->height), $color);
}
for ($i = 0; $i < 6; $i++) {
$color = imagecolorallocate($this->img, 0, 0, 0);
imagestring($this->img, mt_rand(1, 5), mt_rand(0, $this->width), mt_rand(0, $this->height), "*", $color);
}
}
private function outPut()
{
ob_clean();
header("Content-type:image/png");
imagepng($this->img);
imagedestroy($this->img);
}
public function gencodeimage()
{
$this->createBg();
$this->createCode();
$this->createLine();
$this->createFont();
$this->outPut();
return true;
}
public function getCode()
{
return strtolower($this->code);
}
}
?>