好吧,這是我博客園上的,真不知道是轉載還是原創!原始地址:http://www.cnblogs.com/cntnn11/archive/2012/09/03/2669145.html
不過,CSDN的編輯器比博客園的好看多了
下午活少,又剛看php的GD庫不久,寫個驗證碼練練手。
沒做什麼修飾,一路直下,no function,no class!
裏邊的函數查手冊吧,完全不會的先去把php的GD庫看一遍。
還是不發首頁。
這是效果圖:
<?php
session_start();
/**
* 一個簡單的加乘驗證碼類
* @author 譚寧寧
* @datetime 2012-09-03
*/
class codeimg
{
public $width = 150;
public $height = 35;
public $num_1 = 1;
public $num_2 = 10;
public $f_file = 'font/msyhbd.ttf';
public $f_size = 13;
public $c_type = 1; //驗證碼類型:1加乘混合出現/2純加法/3純乘法。默認爲1
public $imgSourc= '';
public $line = true;
public $lineNum = 0;
private $sess = ''; //存入session的值
private $dev = FALSE;//調試模式,也就是不輸出header("content-type: image/png;");也不生成圖片。測試的
function __construct()
{
$this->genImg();
}
function genImg()
{
$this->imgSourc = $this->createImgSourc();
if(!self::$this->dev)
{
header("content-type: image/png;");
imagepng($this->imgSourc);
imagedestroy($this->imgSourc);
}
}
function createImgSourc()
{
$this->imgSourc = imagecreate($this->width, $this->height);
$bgcolor = imagecolorallocate($this->imgSourc, 255, 255, 255);
//是否生成干擾線
if($this->line)
{
$this->genLine();
}
$text = $this->genStr();
$strlen = mb_strlen($text);
$y = intval(($this->height-$this->f_size));
$x = intval(($this->height-$strlen));
$textColor = imagecolorallocate($this->imgSourc, rand(0, 125), rand(0, 125), rand(0, 125));
imagettftext($this->imgSourc, $this->f_size, 0, $x, $y, $textColor, $this->f_file, $text);
return $this->imgSourc;
}
/**
* 干擾線線的生成
* 根據$this->lineNum決定生成多少條線,默認爲隨機生成5~12條
*/
function genLine()
{
$lineNum = empty($this->lineNum) ? rand(5, 12) : $this->lineNum;
for($i = 1; $i <= $lineNum; $i++ )
{
$linecolor = imagecolorallocate($this->imgSourc, rand(0 , 255), rand(0, 255), rand(0, 255));
imageline($this->imgSourc, rand(1 , $this->width), rand(1, $this->height), rand(1, $this->width), rand(1, $this->height), $linecolor);
}
}
/**
* 生成圖片裏的內容
* @return string
*/
function genStr()
{
$operArr = array('加', '乘');
$operNum = $this->c_type === 2 ? 0 : ($this->c_type === 3 ? 1 : rand(0, 1));
$numArr[0] = rand(intval($this->num_1), intval($this->num_2));
$numArr[1] = rand(intval($this->num_1), intval($this->num_2));
if($operNum === 1)
{
$numArr[2] = intval($numArr[0])*intval($numArr[1]);
}
else
{
$numArr[2] = intval($numArr[0])+intval($numArr[1]);
}
$temp_num = rand(0, 2);
self::$this->sess = $numArr[$temp_num];
$numArr[$temp_num] = '**';
$string = $numArr[0].' '.$operArr[$operNum].' '.$numArr[1].' = '.$numArr[2];
return $string;
}
function getValue()
{
return self::$this->sess;
}
}
header("content-type: text/html; charset=utf-8");
$objimg = new codeimg();
$_SESSION['scode'] = $objimg->getValue();
?>