備注:將公共頁面加入session_start();
<?php
session_start();
ini_set('display_errors', 'Off');
class CCheckCodeFile
{
//驗證碼位數 www.2cto.com
var $mCheckCodeNum = 4;
//產生的驗證碼
var $mCheckCode = '';
//驗證碼的圖片
var $mCheckImage = '';
//干擾像素
var $mDisturbColor = '';
//驗證碼的圖片寬度
var $mCheckImageWidth = '80';
//驗證碼的圖片寬度
var $mCheckImageHeight = '20';
//輸出頭
function OutFileHeader()
{
header ("Content-type: image/png");
}
//產生驗證碼
function CreateCheckCode()
{
//$this->mCheckCode = strtoupper(substr(md5(rand()),0,$this->mCheckCodeNum));
$this->mCheckCode = strtoupper(substr(rand(0,9999999999),0,$this->mCheckCodeNum));
session_cache_expire(60);
session_start();
$_SESSION["code_str"] = $this->mCheckCode;
return $this->mCheckCode;
}
//產生驗證碼圖片
function CreateImage()
{
$this->mCheckImage = @imagecreate ($this->mCheckImageWidth,$this->mCheckImageHeight);
imagecolorallocate ($this->mCheckImage, 255, 255, 255);
return $this->mCheckImage;
}
//設置圖片的干擾像素
function SetDisturbColor()
{
for ($i=0;$i<=128;$i++)
{
$this->mDisturbColor = imagecolorallocate ($this->mCheckImage, rand(0,255), rand(0,255), rand(0,255));
imagesetpixel($this->mCheckImage,rand(1,100),rand(1,100),$this->mDisturbColor);
}
}
//設置驗證碼圖片的大小\寬\高
function SetCheckImageWH($width,$height)
{
if($width==''||$height=='')return false;
$this->mCheckImageWidth = $width;
$this->mCheckImageHeight = $height;
return true;
}
//在驗證碼圖片上逐個畫上驗證碼
function WriteCheckCodeToImage()
{
for ($i=0;$i<=$this->mCheckCodeNum;$i++)
{
$bg_color = imagecolorallocate ($this->mCheckImage, rand(0,255), rand(0,255), rand(0,255));
$x = floor($this->mCheckImageWidth/$this->mCheckCodeNum)*$i;
$y = rand(0,$this->mCheckImageHeight-15);
imagechar ($this->mCheckImage, 5, $x, $y, $this->mCheckCode[$i], $bg_color);
}
}
//輸出驗證碼圖片
function OutCheckImage()
{
$this ->OutFileHeader();
$this ->CreateCheckCode();
$this ->CreateImage();
$this ->SetDisturbColor();
$this ->WriteCheckCodeToImage();
imagepng($this->mCheckImage);
imagedestroy($this->mCheckImage);
}
}
$c_check_code_image = new CCheckCodeFile();
//$c_check_code_image ->SetCheckImageWH(100,50);//設置顯示驗證碼圖片的尺寸
$c_check_code_image->OutCheckImage();
?>
使用方法:
<tr>
<td align="center" valign="middle">驗證碼</td>
<td align="center" valign="middle"><input name="number" type="text" style="width:80px;">
<img src="code.php" id="yzm" onclick="this.src='code.php?abc='+Math.random()" alt="圖片看不清?點擊重新得到驗證碼" style="cursor:hand;" />
</td>
</tr>
驗證是否正確
session_start();
if($_POST["number"] == $_SESSION["code_str"]){
// echo("驗證碼正確");
}else{
echo "
<script>
var s=10;
function ok()
{
s--;
document.getElementById('tips').innerHTML=s;
if(s==0)
{
clearTimeout(t);
history.go(-1);
}
}
var t=setInterval('ok()',1000);
</script>
" . "請輸入的驗證碼,請重新輸入<span id='tips'></span>秒之後,將為您跳轉到<a href=\"javascript:history.go(-1)\">上一頁</a>";
}
摘自 http://itsafe.org/?p=384