Home > Backend Development > PHP Tutorial > How to generate verification code in PHP graphics and image processing?

How to generate verification code in PHP graphics and image processing?

PHPz
Release: 2018-12-18 09:24:13
forward
2352 people have browsed it

The content of this article is to introduce how to generate verification code in PHP graphics and image processing? It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Nowadays, verification codes are increasingly indispensable on the Internet. I wonder if you guys know that you can use the GD library of php to generate verification codes.

First introduce a few functions that need to be used.

1.imagesetpixel()

This function can draw pixels. In the verification code, we call it "noise", it is simply an artifact. I don’t know if you guys have remembered that the dots on the verification code are generated using this function.

2.str_shuffle()

Use this to scramble the string, and then use substr() to intercept a given number of digits to generate a random string.

Example:

<?php

$img = imagecreatetruecolor(100, 50);
$black = imagecolorallocate($img, 0x00, 0x00, 0x00);
$green = imagecolorallocate($img, 0x00, 0xFF, 0x00);
$white = imagecolorallocate($img, 0xFF, 0xFF, 0xFF);
imagefill($img, 0, 0, $white);
//生成随机的验证码
$code = make(5);
imagestring($img, 5, 10, 10, $code, $black);
//加入噪点干扰
for ($i = 0; $i < 300; $i++) {
    imagesetpixel($img, rand(0, 100), rand(0, 100), $black);
    imagesetpixel($img, rand(0, 100), rand(0, 100), $green);
}
//加入线段干扰
for ($n = 0; $n <= 1; $n++) {
    imageline($img, 0, rand(0, 40), 100, rand(0, 40), $black);
    imageline($img, 0, rand(0, 40), 100, rand(0, 40), $white);
}
//输出验证码
header("content-type: image/png");
imagepng($img);
//销毁图片
imagedestroy($img);
//生产随机验证码的函数
function make($length)
{
    $code = &#39;abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789&#39;;
    return substr(str_shuffle($code), 0, $length);
}
Copy after login

Rendering:

                                                                                                                                                                                         

How to generate verification code in PHP graphics and image processing?

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template