PHP验证码生成原理和实现_php实例

WBOY
Freigeben: 2016-06-07 17:09:34
Original
713 Leute haben es durchsucht

验证码在表单实现越来越多了,但是用js的写的验证码,总觉得不方便,所以学习了下php实现的验证码。好吧,其实是没有事情干,但是又不想浪费时间,所以学习了下php实现验证码。正所谓,技多不压身。而且,也可以封装成一个函数,以后使用的时候也是很方便的,当然现在未封装。

先给大家附上一张效果图:

由于注册的时候常常会用到注册码来防止机器恶意注册,这里我发表一个产生png图片验证码的基本图像,很简陋但思想很清晰:

1、产生一张png的图片
2、为图片设置背景色
3、设置字体颜色和样式
4、产生4位数的随机的验证码
5、把产生的每个字符调整旋转角度和位置画到png图片上
6、加入噪点和干扰线防止注册机器分析原图片来恶意注册
7、输出图片
8、释放图片所占内存

authcode.php文件

代码

<&#63;php
session_start ();
header ( 'Content-type: image/png' );
//创建图片
$im = imagecreate($x=130,$y=45 );
$bg = imagecolorallocate($im,rand(50,200),rand(0,155),rand(0,155)); //第一次对 imagecolorallocate() 的调用会给基于调色板的图像填充背景色
$fontColor = imageColorAllocate ( $im, 255, 255, 255 ); //字体颜色
$fontstyle = 'rock.ttf'; //字体样式,这个可以从c:\windows\Fonts\文件夹下找到,我把它放到和authcode.php文件同一个目录,这里可以替换其他的字体样式
//产生随机字符
for($i = 0; $i < 4; $i ++) {
$randAsciiNumArray = array (rand(48,57),rand(65,90));
$randAsciiNum = $randAsciiNumArray [rand ( 0, 1 )];
$randStr = chr ( $randAsciiNum );
imagettftext($im,30,rand(0,20)-rand(0,25),5+$i*30,rand(30,35),$fontColor,$fontstyle,$randStr);
$authcode .= $randStr; 
}
$_SESSION['authcode'] = $randFourStr;//用户和用户输入的验证码做比较
//干扰线
for ($i=0;$i<8;$i++){
$lineColor = imagecolorallocate($im,rand(0,255),rand(0,255),rand(0,255));
imageline ($im,rand(0,$x),0,rand(0,$x),$y,$lineColor);
}
//干扰点
for ($i=0;$i<250;$i++){
imagesetpixel($im,rand(0,$x),rand(0,$y),$fontColor);
}
imagepng($im);
imagedestroy($im); 
&#63;>
Nach dem Login kopieren

以上是针对PHP验证码生成原理和实现的相关知识,希望对大家有所帮助。

Verwandte Etiketten:
Quelle:php.cn
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!