首页 > 开发 > PHP > 正文

全面解析PHP验证码的实现原理 附php验证码小案例

2024-05-04 22:28:45
字体:
来源:转载
供稿:网友

拓展

我们需要开启gd拓展,可以使用下面的代码来查看是否开启gd拓展。

<?phpecho "Hello World!!!!";echo phpinfo();?>

然后在浏览器上Ctrl+F查找gd选项即可验证自己有没有装这个拓展,如果没有的话,还需要自己全装一下这个拓展。

背景图

imagecreatetruecolor

默认生成黑色背景

<?php// 使用gd的imagecreatetruecolor();创建一张背景图$image = imagecreatetruecolor(100,30);// 在显示这张图片的时候一定要先声明头信息header('content-type:image/png');imagepng($image);// 释放资源,销毁执行对象imagedestroy($image);

imagecolorallocate

创建一个填充色,并用imagefill(image,x,y,color)方法来附着。

<?php// 使用gd的imagecreatetruecolor();创建一张背景图$image = imagecreatetruecolor(100,30);// 生成填充色$bgcolor = imagecolorallocate($image,255,255,255);// 将填充色填充到背景图上imagefill($image,0,0,$bgcolor);// 在显示这张图片的时候一定要先声明头信息header('content-type:image/png');imagepng($image);// 释放资源,销毁执行对象imagedestroy($image);

imagepng

在使用这个方法之前,一定要先设置头信息,否则不会正常的显示图片 

imagedestory(image)

适时的释放资源会减轻对服务器请求的压力。 

简易数字验证码

imagecolorallocate

生成颜色信息,方便待会的赋予处理。

$fontcolor=imagecolorallocate($image,rand(0,255),rand(0,255),rand(0,255));

imagestring

把内容信息写到图片的相应位置上。

imagestring($image,$fontsize,$x,$y,$fontcontent,$fontcolor);

增加识别干扰

//增加点// 生成一些干扰的点,这里是200个for($i=0;$i<200;$i++){  $pointcolor = imagecolorallocate($image,rand(50,255),rand(50,255),rand(50,255));  imagesetpixel($image,rand(0,100),rand(0,30),$pointcolor);}// 增加线// 生成一些干扰线 这里是5个for($i=0;$i<5;$i++){  // 设置为浅色的线,防止喧宾夺主  $linecolor = imagecolorallocate($image,rand(50,255),rand(50,255),rand(50,255));  imageline($image,rand(0,99),rand(0,29),rand(0,99),rand(0,29),$linecolor);}

 数字字母混合验证码

<?php// 使用gd的imagecreatetruecolor();创建一张背景图$image = imagecreatetruecolor(100,40);// 生成填充色$bgcolor = imagecolorallocate($image,255,255,255);// 将填充色填充到背景图上imagefill($image,0,0,$bgcolor);//////// 生成随机4位字母以及数字混合的验证码for($i=0;$i<4;$i++){  $fontsize = rand(6,8);  $fontcolor = imagecolorallocate($image,rand(0,255),rand(0,255),rand(0,255));  // 为了避免用户难于辨认,去掉了某些有歧义的字母和数字  $rawstr = 'abcdefghjkmnopqrstuvwxyz23456789ABCDEFGHJKLMNOPQRSTUVWXYZ';  $fontcontent = substr($rawstr,rand(0,strlen($rawstr)),1);  // 避免生成的图片重叠  $x += 20;  $y = rand(10,20);  imagestring($image,$fontsize,$x,$y,$fontcontent,$fontcolor);  }// 生成一些干扰的点,这里是200个for($i=0;$i<200;$i++){  $pointcolor = imagecolorallocate($image,rand(50,255),rand(50,255),rand(50,255));  imagesetpixel($image,rand(0,100),rand(0,30),$pointcolor);}// 生成一些干扰线 这里是4个for($i=0;$i<4;$i++){  // 设置为浅色的线,防止喧宾夺主  $linecolor = imagecolorallocate($image,rand(50,255),rand(50,255),rand(50,255));  imageline($image,rand(0,99),rand(0,29),rand(0,99),rand(0,29),$linecolor);}header('content-type:image/png');imagepng($image);// 释放资源,销毁执行对象imagedestroy($image);            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表