如何用php实现验证码的制作

如题所述

<?php
//验证码:文本类型为图像
header("content-type:image/png");
define('TYPE',3);//1.字母 2.字母数字 3.数字 4.逻辑 5.汉字
session_start();
//创建画布
$img = imagecreatetruecolor(90,33);
//创建颜色
//$bgcolor = imagecolorallocate($img,rand(200,255),rand(200,255),rand(200,255));
$bgcolor = imagecolorallocate($img,255,255,255);
$textcolor = imagecolorallocate($img,rand(0,100),rand(0,100),rand(0,100));
//填充颜色到画布
imagefill($img,0,0,$bgcolor);
//创建但像素的点为干扰项
//for($i=0;$i<100;$i++){
// $pixelcolor = imagecolorallocate($img,rand(150,200),rand(150,200),rand(150,200));
// imagesetpixel($img,rand(0,70),rand(0,30),$pixelcolor);
//}
//
////划线
//$linecolor = imagecolorallocate($img,255,0,0);
//imageline($img,0,0,70,30,$linecolor);
//
////多边形
// $col_poly = imagecolorallocate ( $img , 0 , 255 , 0 );
// imagepolygon ( $img ,
// array (
// 5 , 5,
// 5, 15 ,
// 20,15,
// 20,5
// ),
// 4 ,
// $col_poly );
////弧线
//$arcColor = imagecolorallocate ( $img , 0 , 0 , 255 );
//imagearc($img,35,15,30,30,0,360,$arcColor);

//创建验证码的内容
//#字母
$letter = range('A','Z');
$letterStr = $letter[rand(0,25)].$letter[rand(0,25)].$letter[rand(0,25)].$letter[rand(0,25)];
//数字字母
$num = range(0,9);
$numberAndLetter = array_merge($letter,$num);
$nal = $numberAndLetter[rand(0,35)].$numberAndLetter[rand(0,35)].$numberAndLetter[rand(0,35)].$numberAndLetter[rand(0,35)];
//#数字
$number = rand(1000,9999);
//#逻辑
$x = rand(1,9);
$y = rand(1,9);
$expression = $x."+".$y."=?";
$sum = $x+$y;
//#汉字
$CH = array('恭喜发财','财源滚滚','财源广进','才高八斗','学富五车','抬头见喜');
$chstr = $CH[rand(0,count($CH)-1)];
switch(TYPE){
case 1 : imagettftext($img,14,0,7,23,$textcolor,'MSYH.TTF',$letterStr);$_SESSION['code']=$letterStr;break;
case 2 : imagettftext($img,14,0,7,23,$textcolor,'MSYH.TTF',$nal);$_SESSION['code']=$nal;break;
case 3 : imagettftext($img,14,0,13,23,$textcolor,'MSYH.TTF',$number);$_SESSION['code']=$number;break;
case 4 : imagettftext($img,14,0,7,23,$textcolor,'MSYH.TTF',$expression);$_SESSION['code']=$sum;break;
case 5 : imagettftext($img,11,0,6,21,$textcolor,'MSYHBD.TTF',$chstr);$_SESSION['code']=$chstr;break;
}
//输入图像到浏览器
imagepng($img);
?>
温馨提示:答案为网友推荐,仅供参考