欢迎光临 - 我的站长站,本站所有资源仅供学习与参考,禁止用于商业用途或从事违法行为!

php教程

PHP类或函数轻松生成验证码教程

php教程 我的站长站 2023-10-22 共9人阅读

生成验证码流程

1、创建验证码图片

2、绘制验证码图片

3、存储输出验证码


1、创建验证码图片

我们可以使用GD库或ImageMagick库生成一个空白的图片。我们先来看一下如何使用GD库生成一个空白的图片。

$image = imagecreate($width, $height);

其中,$width和$height是图片的宽度和高度。这个函数会返回一个空白的图片资源,我们可以在这个图片上绘制验证码。

2、绘制验证码图片

我们可以使用GD库或ImageMagick库,在图片上随机绘制字符或数字。我们先来看一下如何使用GD库在图片上绘制验证码。

$bg_color = imagecolorallocate($image, 255, 255, 255); // 设置背景颜色
$text_color = imagecolorallocate($image, 0, 0, 0); // 设置文字颜色
for($i = 0; $i < $length; $i++){
    $text = substr($code, $i, 1);
    $x = $i * $font_size + 10;
    $y = rand(5, $height - $font_size);
    imagestring($image, $font_size, $x, $y, $text, $text_color);
}

其中,$length是验证码的长度,$code是验证码内容,$font_size是字体大小。这个代码块会在图片上随机绘制验证码,并将验证码存储到$code变量中。

3、存储验证码

我们将生成的验证码存储到session或Cookie中,以便稍后进行验证。

session_start();
$_SESSION['captcha'] = $code;

这个代码块将生成的验证码存储到了session中,方便稍后进行验证。

4、输出验证码

我们可以使用imagepng函数输出生成的验证码,并销毁图片资源。

header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);

这个代码块会输出生成的验证码图片。

完整示例代码

<?php
class Captcha {
    private $code; // 存储验证码
    private $width = 100; // 图片宽度
    private $height = 30; // 图片高度
    private $length = 4; // 验证码长度
    function __construct($length = 4, $width = 100, $height = 30) {
        $this->length = $length;
        $this->width = $width;
        $this->height = $height;
        $this->code = $this->generateCode();
    }
    private function generateCode() {
        $code = '';
        for($i=0;$i<$this->length;$i++){
            $code .= rand(0,9);
        }
        return $code;
    }
    public function getCode() {
        return $this->code;
    }
    public function createImage() {
        $image = imagecreate($this->width, $this->height);
        $bg = imagecolorallocate($image, 255, 255, 255);
        $textcolor = imagecolorallocate($image, 0, 0, 0);
        imagestring($image, 5, 30, 8, $this->code, $textcolor);
        header("Content-type: image/png");
        imagepng($image);
        imagedestroy($image);
    }
    public function saveCode() {
        session_start();
        $_SESSION['captcha'] = $this->code;
    }
}

我们定义了四个私有属性:$code用于存储验证码,$width和$height用于设置图片的宽度和高度,$length用于设置验证码的长度。我们使用构造函数初始化