开始之前首先安装php开发环境,这里使用xampp
打开php的gd2图形库支持(在php.ini,中搜索“php_gd2.dll”,找到“;extension=php_gd2.dll”并去掉句首的分号) 。http://127.0.0.1/dashboard/phpinfo.php
表明已经安装了gd库。核心:img.php
这个页面生成一张验证码并将正确数值写入Session随机一个4位验证码$check=rand(1000,9999);将生成的验证码写入sessionSession_start();$_SESSION[‘check’]=$check;创建一张图片$im = imagecreate(80,30);由于这种图片的背景默认是黑色的所以我们要用白色填充。Imagefill($im,0,0,ImageColorAllocate($im,255,255,255));使用imageline随机绘制两条实线$y1=rand(0,30); $y2=rand(0,30); $y3=rand(0,30); $y4=rand(0,30); imageline($im,0,$y1,70, $y3,000); imageline($im,0,$y2,70, $y4,000);在随机位置绘制文字$strx=rand(3,15); $stry=rand(2,15); imagestring($img,5,$strx,$stry,substr($check,0,1),ImageColorAllocate($img,34,87,100)); $strx+=rand(15,20);$stry=rand(2,15); imagestring($img,5,$strx,$stry,substr($check,1,1),ImageColorAllocate($img,781,117,78)); $strx+=rand(15,20);$stry=rand(2,15); imagestring($img,5,$strx,$stry,substr($check,2,1),ImageColorAllocate($img,160,40,40)); $strx+=rand(15,20);$stry=rand(2,15); imagestring($img,5,$strx,$stry,substr($check,3,1),ImageColorAllocate($img,25,55,10));输出图像Header('Content-type: image/PNG'); ImagePNG($img);结束,下面是完整代码
用户界面:index.php
检查:action.php这一步要将用户输入数值与session中的数值进行比对相等,输出“正确”不相等,输出“不正确”
如果错误,会输出不正确