当前位置:首页 > 叨叨念念 > PHP验证码的实例

PHP验证码的实例

叨叨念念 / 星之宇 / 2021-10-3 15:15 / 浏览:1517 / 评论:0

PHP生成简单的验证码实例。

验证码图片的生成是验证码功能的核心,需要生成一个随机字符,并将其渲染为图像展示给用户。PHP中可以使用GD库来生成验证码图片。


GD库是一种用于动态创建图像的PHP扩展,它提供了多种函数可以用于创建图像、修改图像、保存图像等操作,通过GD库可以很方便地创建验证码图片。


使用GD生成验证码步骤:

1、创建图片大小,背景颜色。

2、生成随机字符串,一般是4~6位之间。

3、将生成的随机字符串加入到图片中。

4、生成干扰点和干扰线等。


验证码代码实例

<?php
session_start();
Header("Content-type: image/PNG");

// 验证码图片的长宽
$width = 120;
$height = 50;

// 创建图片
$img = imagecreate($width,$height);
// 定义背景,随机背景色
imagecolorallocate($img,rand(200,255),rand(200,255),rand(200,255)); 

// 定义验证码长度
$codelen = 4;
// 字体文件
$font = 'Arial-Narrow.ttf';
// 验证码字符串库
$chars = '346789ABCDEFGHJKLMNPQRTUVWXY';
// 验证码字符串
$randCode = '';
$_x = $width / $codelen;
$_y = $height / 2;
for($i=0;$i<$codelen;$i++){
  // 获取随机字符
  $code = substr($chars, rand(0, strlen($chars) - 1), 1);
  $randcode .= $code;
  // 随机字符串颜色
  $fontcolor = imagecolorallocate($img, rand(1,120), rand(1,120), rand(1,120)); 
  // 随机字符串加入图片
  imagettftext($img,24,rand(-30,30),$_x*$i+rand(3,6),$_y+rand(0,24),$fontcolor,$font,$code);
}

//生成干扰点
for($i=0;$i<=$width;$i++){
  $pointcolor = imagecolorallocate($img,rand(0,255),rand(0,255),rand(0,255));//点的颜色
  imagesetpixel($img,rand(0,$width-1),rand(0,$height-1),$pointcolor);// 水平地画一串像素点
}

//生成干扰线
for ($i=0;$i<=$codelen;$i++){
  $linecolor = imagecolorallocate($img,rand(0,255),rand(0,255),rand(0,255));//线的颜色
  imageline($img,rand(0,$width),rand(0,$height),rand(0,$width),rand(0,$height),$linecolor);//画一条线段
}

// 写入SESSION
$_SESSION['captcha'] = strtoupper($randCode);

// 显示图片
ImagePNG($img);
// 释放图片资源
ImageDestroy($img);

exit;

目前有 0 条评论

    • 昵称
    • 邮箱
    • 网址