PHP 生成图片验证码

2016-02-04
次阅读
1 分钟阅读时长

验证码用于用户恶意刷注册、评论等,所以在网站中,验证码是颇为重要的东西。

今天就来讲下如何用 PHP 创建一个验证码。

先生成四位验证码,将生成的验证码赋值给session,用于验证:

$code = '';
for ($i = 0; $i < 4; $i++) {
    $code . =rand(0, 9);
}
$_SESSION['code'] = $code;

也可以直接使用 rand(1000, 9999) 直接生成。

然后再使用 imagecreate() 创建画布:

$im = imagecreate(50,15);    //imagecreate(宽度 ,高度);

然后再定义颜色值:

$bg = imagecolorallocate($im, 255, 255, 255);
$te = imagecolorallocate($im, 255, 0, 0);

再将生成的 4 位验证码画在画布上:

imagestring($im, 6, 3, 2, $code, $te);

最后输出图像:

header("Content_type: image/png");
imagejpeg($im);

完整代码:

<?php
session_start();
$code = '';
for ($i = 0; $i < 4; $i++) {
    $code .= rand(0, 9);
}
$_SESSION['code'] = $code;

$im = imagecreate(50, 15);    //imagecreate(宽度 ,高度);
$bg = imagecolorallocate($im, 255, 255, 255);
$te = imagecolorallocate($im, 255, 0, 0);
imagestring($im, 6, 3, 2, $code, $te);
header("Content_type: image/png");
imagejpeg($im);

将以上代码保存为 img_code.php,在 HTML 页面插入一句代码:

<img src="img_code.php">

是不是感觉很简单呢?这只是比较基础图片验证码,容易被一些软件所识别,所以要加入噪点和干扰线防止注册机器分析原图片来恶意破解验证码。

这是一篇过去很久的文章,其中的信息可能已经有所发展或是发生改变。

本文作者:她和她的猫
本文地址https://her-cat.com/posts/2016/02/04/php-generate-image-captcha/
版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明出处!