>
PHP验证码
2021-02-01 15:32
PHP
  • 778
  • 527
  • 64
  • 51

验证码的含义及作用:

证码(CAPTCHA)是“Completely Automated Public Turing test to tell Computers and Humans Apart”(全自动区分计算机和人类的图灵测试)的缩写,是一种区分用户是计算机还是人的公共全自动程序。可以防止:恶意破解密码、刷票、论坛灌水,有效防止某个黑客对某一个特定注册用户用特定程序暴力破解方式进行不断的登陆尝试,实际上用验证码是现在很多网站通行的方式,我们利用比较简易的方式实现了这个功能。这个问题可以由计算机生成并评判,但是必须只有人类才能解答。由于计算机无法解答CAPTCHA的问题,所以回答出问题的用户就可以被认为是人类。

我们很多的网站比如注册登录这些都经常用到验证码 不管任何语言的有验证码。

今天就用PHP来写一个验证码的示列:

写验证码我们先来了解下一些函数:

//(1)创建一个新的真彩色图像。
resource imagecreatetruecolor ( int $width , int $height )
width - 图像宽度。
height - 图像高度。

//(2)图像分配颜色
int imagecolorallocate ( resource $image , int $red , int $green , int $blue )
red,green 和 blue 分别是所需要的颜色的红,绿,蓝成分。

//(3)在指定的坐标处绘制像素。
bool imagesetpixel ( resource $image , int $x , int $y , int $color )
image - 由图像创建函数(如imagecreatetruecolor())返回的图像资源。
x-x坐标。
y-y坐标。
color - 使用imagecolorallocate()创建的颜色标识符。

//(4)在两个给定点之间绘制一条线段。
bool imageline ( resource $image , int $x1 , int $y1 , int $x2 , int $y2 , int $color )
image - 由图像创建函数(如imagecreatetruecolor())返回的图像资源。
x1 - 第一点的x坐标。
y1 - 第一点的y坐标。
x2 - 第二点的x坐标。
y2 - 第二点的y坐标。
color - 线条颜色。使用imagecolorallocate()创建的颜色标识符。

//(5)使用TrueType字体将给定文本写入图像。
array imagettftext ( resource $image , float $size , float $angle , int $x , int $y , int $color ,
 string $fontfile , string $text )
//imagettftext()函数语法。
//使用指定的字体文件绘制文字(参数缺一不可)
//参数1:画布资源名称
//参数2:字体大小
//参数3:字体倾斜的角度
//参数4:文字的x坐标
//参数5:文字的y坐标
//参数6:文字的颜色
//参数7:字体文件
//参数8:绘制的文字

//(6)释放图像资源
imagedestroy(resource $image)

验证码代码如下:

$heigth=40;
$width=120;
$img=imagecreatetruecolor($width,$heigth);//1. 创建一个画布
$color_bg=imagecolorallocate($img,rand(150,255),200,200);//创建背景色
imagefill($img,0,0,$color_bg);//设置画布背景色
//循环绘制点
for ($i=0;$i<500;$i++){
    //imagesetpixel()函数语法。
    //bool imagesetpixel ( resource $image , int $x , int $y , int $color )
    imagesetpixel($img,rand(0,$width-1),rand(0,$heigth-1),imagecolorallocate($img,rand(100,255),rand(100,255),
    rand(100,255)));//绘制点
}
//循环绘制线
for ($i=0;$i<10;$i++) {
    imageline($img, rand(0, $width / 2), rand(0, $heigth), rand($width / 2, $width), rand(0, $heigth), 
    imagecolorallocate($img, rand(100, 255), rand(100, 255), rand(100, 255)));//绘制线
}
//文字颜色
$imgcolor=imagecolorallocate($img,rand(100,255),rand(100,255),rand(100,255));
//定义字母数组
$text=array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
//循环随机获取字母
for ($i=0;$i<4;$i++){
    $num=rand(0,count($text)-1);
    $textstring.=$text[$num]."  ";
}
imagettftext($img,30,3,rand(5,10),rand(30,35),$imgcolor,'SpicyPumpkin.ttf',
$textstring);
imagejpeg($img);//输出图片
//在图像的所有资源使用完毕后,通常需要释放图像处理所占用的内存。
//imagedestroy(resource $image)函数来释放图像资源
imagedestroy($img);

效果如下:

image.png

全部留言 ()
返回
顶部