Home Backend Development PHP Tutorial Summary of several methods for generating graphic verification codes in PHP_PHP Tutorial

Summary of several methods for generating graphic verification codes in PHP_PHP Tutorial

Jul 13, 2016 am 10:46 AM
php use several kinds graphics Library Open an account Summarize us method generate code need verify

To generate the graphical verification code, you need to use the php GD library. If you do not have an account with the GD library, we need to find extension=php_gd2.dll in the php.ini file and remove the previous;. Then restart the apache or iis environment.

Let’s first check whether our php has the gd library turned on.

The code is as follows Copy code
 代码如下 复制代码

if(extension_loaded('gd')) {
echo '你可以使用gd
';
  foreach(gd_info() as $cate=>$value)
    echo "$cate: $value
";
}else
  echo '你没有安装gd扩展';
?>

if(extension_loaded('gd')) {

echo 'You can use gd
';

foreach(gd_info() as $cate=>$value)
echo "$cate: $value
";

}else
 代码如下 复制代码

/**
* vCode(m,n,x,y) m个数字 显示大小为n 边宽x 边高y
* 自己改写记录session $code
*/
session_start();
vCode(4, 15); //4个数字,显示大小为15

function vCode($num = 4, $size = 20, $width = 0, $height = 0) {
!$width && $width = $num * $size * 4 / 5 + 5;
!$height && $height = $size + 10;
// 去掉了 0 1 O l 等
$str = "23456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVW";
$code = '';
for ($i = 0; $i < $num; $i++) {
$code .= $str[mt_rand(0, strlen($str)-1)];
}
// 画图像
$im = imagecreatetruecolor($width, $height);
// 定义要用到的颜色
$back_color = imagecolorallocate($im, 235, 236, 237);
$boer_color = imagecolorallocate($im, 118, 151, 199);
$text_color = imagecolorallocate($im, mt_rand(0, 200), mt_rand(0, 120), mt_rand(0, 120));
// 画背景
imagefilledrectangle($im, 0, 0, $width, $height, $back_color);
// 画边框
imagerectangle($im, 0, 0, $width-1, $height-1, $boer_color);
// 画干扰线
for($i = 0;$i < 5;$i++) {
$font_color = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
imagearc($im, mt_rand(- $width, $width), mt_rand(- $height, $height), mt_rand(30, $width * 2), mt_rand(20, $height * 2), mt_rand(0, 360), mt_rand(0, 360), $font_color);
}
// 画干扰点
for($i = 0;$i < 50;$i++) {
$font_color = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
imagesetpixel($im, mt_rand(0, $width), mt_rand(0, $height), $font_color);
}
// 画验证码
@imagefttext($im, $size , 0, 5, $size + 3, $text_color, 'c:WINDOWSFontssimsun.ttc', $code);
$_SESSION["VerifyCode"]=$code;
header("Cache-Control: max-age=1, s-maxage=1, no-cache, must-revalidate");
header("Content-type: image/png;charset=gb2312");
imagepng($im);
imagedestroy($im);
}

?>

echo 'You do not have gd extension installed'; ?>
If there is return information, it is correct and can be used frequently Example 1
The code is as follows Copy code
/**<🎜> * vCode(m,n,x,y) m numbers, display size is n, side width x, side height y<🎜> * Rewrite the record session $code<🎜> ​*/<🎜> session_start(); <🎜> vCode(4, 15); //4 numbers, display size is 15<🎜> <🎜>function vCode($num = 4, $size = 20, $width = 0, $height = 0) {<🎜> !$width && $width = $num * $size * 4 / 5 + 5;<🎜> !$height && $height = $size + 10; <🎜> // Removed 0 1 O l etc. <🎜> $str = "23456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVW";<🎜> $code = '';<🎜> for ($i = 0; $i < $num; $i++) {<🎜> $code .= $str[mt_rand(0, strlen($str)-1)];<🎜> } <🎜> // Draw image<🎜> $im = imagecreatetruecolor($width, $height); <🎜> // Define the color to be used <🎜> $back_color = imagecolorallocate($im, 235, 236, 237);<🎜> $boer_color = imagecolorallocate($im, 118, 151, 199);<🎜> $text_color = imagecolorallocate($im, mt_rand(0, 200), mt_rand(0, 120), mt_rand(0, 120)); <🎜> // Draw background<🎜> imagefilledrectangle($im, 0, 0, $width, $height, $back_color); <🎜> // Draw border<🎜> imagerectangle($im, 0, 0, $width-1, $height-1, $boer_color); <🎜> //Draw interference lines<🎜> for($i = 0;$i < 5;$i++) {<🎜> $font_color = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));<🎜> imagearc($im, mt_rand(- $width, $width), mt_rand(- $height, $height), mt_rand(30, $width * 2), mt_rand(20, $height * 2), mt_rand(0, 360 ), mt_rand(0, 360), $font_color);<🎜> } <🎜> // Draw interference points<🎜> for($i = 0;$i < 50;$i++) {<🎜> $font_color = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));<🎜> imagesetpixel($im, mt_rand(0, $width), mt_rand(0, $height), $font_color);<🎜> } <🎜> // Draw verification code<🎜> @imagefttext($im, $size, 0, 5, $size + 3, $text_color, 'c:WINDOWSFontssimsun.ttc', $code);<🎜> $_SESSION["VerifyCode"]=$code; <🎜> header("Cache-Control: max-age=1, s-maxage=1, no-cache, must-revalidate");<🎜> header("Content-type: image/png;charset=gb2312");<🎜> imagepng($im);<🎜> imagedestroy($im);<🎜> }<🎜> <🎜>?>

Example 2

An example of generating a verification code developed using PHP, combined with session and GD library extensions (recommended by w3c), which can be easily used in projects. And the style is beautiful //First open the session
session_start();
//Define the length & width of the verification code displayed in the front desk
$image_width = 120;
$image_height = 40;
$characters_on_image = 6;
$font = './monofont.ttf';

//The characters that can be used in the CAPTCHA code.
//avoid confusing characters (l 1 and i for example)
$possible_letters = '23456789bcdfghjkmnpqrstvwxyz';
$random_dots = 10;
$random_lines = 30;
$captcha_text_color="0x142864";
$captcha_noice_color = "0x142864";
//Define the string to generate the verification code
$code = '';

$i = 0;
while ($i < $characters_on_image) {
$code .= substr($possible_letters, mt_rand(0, strlen($possible_letters)-1), 1);
$i++;
}

$font_size = $image_height * 0.75;
$image = @imagecreate($image_width, $image_height);

/* setting the background, text and noise colors here */
$background_color = imagecolorallocate($image, 255, 255, 255);

$arr_text_color = hexrgb($captcha_text_color);
$text_color = imagecolorallocate($image, $arr_text_color['red'],
         $arr_text_color['green'], $arr_text_color['blue']);

$arr_noice_color = hexrgb($captcha_noice_color);
$image_noise_color = imagecolorallocate($image, $arr_noice_color['red'],
         $arr_noice_color['green'], $arr_noice_color['blue']);

/* generating the dots randomly in background */
for( $i=0; $i<$random_dots; $i++ ) {
imagefilledellipse($image, mt_rand(0,$image_width),
mt_rand(0,$image_height), 2, 3, $image_noise_color);
}

/* generating lines randomly in background of image */
for( $i=0; $i<$random_lines; $i++ ) {
imageline($image, mt_rand(0,$image_width), mt_rand(0,$image_height),
mt_rand(0,$image_width), mt_rand(0,$image_height), $image_noise_color);
}

/* create a text box and add 6 letters code in it */
$textbox = imagettfbbox($font_size, 0, $font, $code);
$x = ($image_width - $textbox[4])/2;
$y = ($image_height - $textbox[5])/2;
imagettftext($image, $font_size, 0, $x, $y, $text_color, $font, $code);

/* Show captcha image in the page html page */
header('Content-Type: image/jpeg');// defining the image type to be shown in browser widow
imagejpeg($image);//showing the image
imagedestroy($image);//destroying the image instance
//Set up session and do verification
$_SESSION['6_letters_code'] = $code;

function hexrgb ($hexstr)
{
$int = hexdec($hexstr);

return array("red" => 0xFF & ($int >> 0x10),
"green" => 0xFF & ($int >> 0x8),
"blue" => 0xFF & $int);
}

I personally recommend the second program code for generating verification codes. Students can try to compare it for reference. The last one is generated by W3C standards and also uses the php gd library.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/632952.htmlTechArticleTo generate the graphical verification code, you need to use the php GD library to generate it. If you do not have an account with the GD library, we need to create it in php.ini Find extension=php_gd2.dll in the file. Just remove the previous ";" and then restart apache or...
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles