1. 程式人生 > >【PHP】實現驗證碼圖片

【PHP】實現驗證碼圖片

將以下藍色部分得程式碼複製命名為checknum.inc.php

<?php
/*
Describe:生成驗證碼的程式碼
Paramters:$count生成驗證碼的位數
return:生成的驗證碼


*/
function CreatCheckNumber($count=4,$st=1){
$checkNum="";//生成的驗證碼


$str="";
$str1="0 1 2 3 4 5 6 7 8 9";
$str2="a b c d e f g h i j k l m n o p q r s t u v w x y z 

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z";
$str3="我 是 驗 證 碼 分 隔 符 為 空 格";
switch($st){
case 1:$str=$str1;break;
case 2:$str=$str2;break;
case 3:$str=$str3;break;
case 4:$str=$str1.' '.$str2;break;
case 5:$str=$str1.' '.$str3;break;
case 6:$str=$str2.' '.$str3;break;
case 7:$str=$str1.' '.$str2.' '.$str3;break;
}
$arr=explode(" ",$str);
for($i=0;$i<$count;$i++)
$checkNum.=$arr[rand(0,count($arr)-1)];
//處理大小寫字母"o"成數字"0".
$checkNum=str_replace("o","0",str_replace("O","0",$checkNum));


return $checkNum;
 
}



?>

再建一個新的頁面命名為CheckNumeber.php

<?php

//宣告:把當前頁面通過寫程式碼的方式作為圖片生成
header("content-type:image/jpeg");
//繪圖
//建立一塊畫布設定寬高度
include_once("
checknum.inc.php");//呼叫驗證碼函式,此處引用!
$chnr=CreatCheckNumber(4,4); 
 //驗證碼的生成字元數和不同組合情況
$fontSize=20;
$fontHigh=$fontSize*1.1;
$width=ceil(strlen($chnr)*($fontSize+1.5));
$height=$fontHigh*1.8;

$im=imagecreate($width,$height);


imagecolorallocate($im,181,214,249);  //背景色
$borCo=imagecolorallocate($im,204,255,0);//邊框色
$pixCo=imagecolorallocate($im,rand(0,255),rand(0,255),rand(0,255));//點色
$lineCo=imagecolorallocate($im,rand(0,255),rand(0,255),rand(0,255));//線色
$fontCo=imagecolorallocate($im,rand(0,255),rand(0,5),rand(0,250));//文字色

//畫邊框
imagerectangle($im,0,0,$width-1,$height-1,$borCo);
//畫點
for($i=1;$i<50;$i++){
imagesetpixel($im,rand(1,$width),rand(1,$height),$pixCo);}
//畫線
for($i=1;$i<3;$i++){
imageline($im,0,rand(1,$height-1),$width,rand(1,$height-1),
$lineCo);}
$font="STSONG.TTF";

for($i=0;$i<=strlen($chnr);$i++){
$sum=mb_substr($chnr,$i,1,'utf-8');

imagettftext($im,$fontSize,5,$i*$fontSize+rand(2,5),

rand($height/1.2,$height/2.5),$fontCo,$font,$sum);


}
//生成圖片
imagejpeg($im);
//釋放資源
imagedestroy($im);


?>