用PHP制作一个简单的验证码

我是一名PHP新手,最近在整一网站,下面是我在注册页面上使用的验证码功能,虽然这个比较简单,但是还是能起到一定的作用。比我原来什么都不知道好很多。

下面是步骤和代码,每个函数都都有注释,对于新手而言比较好懂:

<?php
//1、打开session
session_start();

//2、创建随机码并保存到SESSION
$num = "";
for($i=0 ; $i<4 ; $i++)
{
$num .= dechex(mt_rand(0,15)); //mt_rand()产生随机数、dechex()转成16进制
}
$_SESSION['code'] = $num;

//3、创建一张图像
$_width = 100;
$_height = 30;
$img = imagecreatetruecolor($_width,$_height); //width,height、生成图片,默认背景为黑色

//4、填充图片背景颜色
$_white = imagecolorallocate($img,255,255,255); //RGB、imagecolorallocate()向图像添加某颜色,每次要在图像上使用某颜色都要使用该函数
imagefill($img,0,0,$_white);      //将$_white颜色填充到图像背景,0,0起始位置

//5、给图像画个框框,个人喜好
$_black = imagecolorallocate($img,0,0,0);
imagerectangle($img,0,0,$_width-1,$_height-1,$_black);  //imagerectangle在图像上画一个矩形,起始坐标-->终止坐标,颜色$_black

//6、加入线条干扰信息
for($i=0 ; $i<5 ; $i++)
{
$rand_color = imagecolorallocate($img,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
imageline($img,mt_rand(0,$_width),mt_rand(0,$_height),mt_rand(0,$_width),mt_rand(0,$_height),$rand_color);//图像上画直线,类似画矩形

}

//7、加入雪花(*)干扰信息
for($i=0 ; $i<10 ; $i++)
{
$rand_color = imagecolorallocate($img,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
imagestring($img,5,mt_rand(0,$_width),mt_rand(0,$_height),"*",$rand_color);    //参数:图像,要添加字样的字体大小,起始坐标,颜色
}

//8、将验证码加入到图片
for($i=0 ;$i<strlen($_SESSION['code']) ; $i++)
{
imagestring($img,5,20+$i*15,mt_rand(0,10),$_SESSION['code'][$i],$rand_color);
}

//9、输出验证码
header("Content-Type:image/png");
imagepng($img);    //显示图像
imagedestroy($img);
?>


参考博客:http://blog.sina.com.cn/s/blog_691051e10100zk18.html








原文地址:https://www.cnblogs.com/MonkeyF/p/2996744.html