Table of Contents
php generates image verification code
Home Backend Development PHP Tutorial Generate image verification code with php_PHP tutorial

Generate image verification code with php_PHP tutorial

Jul 13, 2016 am 09:51 AM
php web picture exist application generate user code important prevent verify

php generates image verification code

Verification code is very important in WEB applications. It is usually used to prevent users from maliciously submitting forms, such as malicious registration and login, malicious forum flooding, etc. This article will explain how to use PHP to generate common verification codes through examples

Let’s take a look at the rough effect first

Then let’s just post the code next

 ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

$image = imagecreatetruecolor(100, 30); //创建画布

$imagecolor = imagecolorallocate($image, 255, 255, 255); //背景色

imagefill($image, 0, 0, $imagecolor); //填充背景色

for($i=0;$i<4;$i ){ //循环4位数

$fontsize = 6;

$fontcolor = imagecolorallocate($image, rand(0, 200), rand(0, 200), rand(0, 200));

$fontcontent = rand(0, 9);

$x = $i*100/4 rand(5, 15);

$y = rand(5, 10);

imagestring($image, $fontsize, $x, $y, $fontcontent, $fontcolor);

}

for($i=0;$i<200;$i ){ //循环 添加干扰点

$pointcolor = imagecolorallocate($image, rand(50, 200), rand(50, 200), rand(50, 200));

$x = rand(1, 99);

$y = rand(1, 29);

imagesetpixel($image, $x, $y, $pointcolor);

}

for($i=0;$i<3;$i ){ //循环 添加干扰线

$linecolor = imagecolorallocate($image, rand(100, 250), rand(100, 250), rand(100, 250));

$x1 = rand(1, 25);

$x2 = rand(50, 75);

$y1 = rand(1, 15);

$y2 = rand(15, 25);

imageline($image, $x1, $y1, $x2, $y2, $linecolor);

}

header("content-type:image/png");

imagepng($image);

imagedestroy($image);

?>

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
<🎜>$image = imagecreatetruecolor(100, 30); //Create canvas<🎜> <🎜>$imagecolor = imagecolorallocate($image, 255, 255, 255); //Background color<🎜> <🎜>imagefill($image, 0, 0, $imagecolor); //Fill the background color<🎜> <🎜>for($i=0;$i<4;$i ){ //Loop 4 digits<🎜> <🎜>$fontsize = 6;<🎜> <🎜>$fontcolor = imagecolorallocate($image, rand(0, 200), rand(0, 200), rand(0, 200));<🎜> <🎜>$fontcontent = rand(0, 9);<🎜> <🎜>$x = $i*100/4 rand(5, 15);<🎜> <🎜>$y = rand(5, 10);<🎜> <🎜>imagestring($image, $fontsize, $x, $y, $fontcontent, $fontcolor);<🎜> <🎜>}<🎜> <🎜>for($i=0;$i<200;$i ){ //Loop to add interference points<🎜> <🎜>$pointcolor = imagecolorallocate($image, rand(50, 200), rand(50, 200), rand(50, 200));<🎜> <🎜>$x = rand(1, 99);<🎜> <🎜>$y = rand(1, 29);<🎜> <🎜>imagesetpixel($image, $x, $y, $pointcolor);<🎜> <🎜>}<🎜> <🎜>for($i=0;$i<3;$i ){ //Loop to add interference lines<🎜> <🎜>$linecolor = imagecolorallocate($image, rand(100, 250), rand(100, 250), rand(100, 250));<🎜> <🎜>$x1 = rand(1, 25);<🎜> <🎜>$x2 = rand(50, 75);<🎜> <🎜>$y1 = rand(1, 15);<🎜> <🎜>$y2 = rand(15, 25);<🎜> <🎜>imageline($image, $x1, $y1, $x2, $y2, $linecolor);<🎜> <🎜>}<🎜> <🎜>header("content-type:image/png");<🎜> <🎜>imagepng($image);<🎜> <🎜>imagedestroy($image);<🎜> <🎜>?>

Let me share with you another method that can generate Chinese verification code

 ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

//1.qi Enable the gd library. The GD library provides a series of APIs for processing images. You can use the GD library to process images or generate images.

// On websites, the GD library is usually used to generate thumbnails or to add watermarks to images or to generate reports on website data.

session_start();

// Convert the GBK encoded string into a UTF-8 string. The reason why the first parameter is written GBK is because the encoding of this php file stored in the host is GBK encoding

// UTF-8 encoding is generally supported by browsers and has strong versatility. Let’s convert it to UTF-8 here

$str = iconv("GBK", "utf-8", "All living things, green waters, green mountains, scenic spots and historic sites, open your mind and you will see clouds and clouds, and happiness will always be with you");

if(!is_string($str) || !mb_check_encoding($str,"utf-8"))

{

exit("Not a string or not utf-8");

}

$zhongwenku_size;

// Get the length of the string in UTF-8 encoding

$zhongwenku_size = mb_strlen($str,"UTF-8");

// Import the above characters into the array

$zhongwenku = array();

for( $i=0; $i<$zhongwenku_size; $i )

{

$zhongwenku[$i] = mb_substr($str, $i,1,"UTF-8");

}

$result = "";

//Four characters to be written on the picture

for($i=0; $i<4; $i )

{

switch (rand(0, 1))

{

case 0:

$result.=$zhongwenku[rand(0, $zhongwenku_size-1)];

break;

case 1:

$result.=dechex(rand(0,15));

break;

}

}

$_SESSION["check"] = $result;

// Create a true color picture with a width of 100 and a height of 30

$img = imagecreatetruecolor(100, 30);

//Assign background color

$bg = imagecolorallocate($img, 0, 0, 0);

//Assign text color

$te = imagecolorallocate($img, 255,255,255);

//Write string on the image

//imagestring($img, rand(3,8), rand(1,70), rand(1,10), $result, $te);

//You can write special fonts on the picture according to the loaded font

imagettftext($img, 13, rand(2, 9), 20 ,20, $te, "MSYH.TTF",$result);

$_SESSION["check"] = $result;

for($i=0; $i<3; $i )

{

// $t = imagecolorallocate($img, rand(0, 255),rand(0, 255),rand(0, 255));

// Draw lines

imageline($img, 0, rand(0, 20), rand(70,100), rand(0, 20), $te);

}

$t = imagecolorallocate($img, rand(0, 255),rand(0, 255),rand(0, 255));

// Add noise to the image

for($i=0; $i<200; $i )

{

imagesetpixel($img, rand(1, 100), rand(1, 30), $t);

}

//Send http header information. Specify that the jpeg in the image is sent this time

header("Content-type: image/jpeg");

// Output jpeg images to the browser

imagejpeg($img);

?>

Let’s give another example

 ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

session_start();

function random($len) {

$srcstr = "1a2s3d4f5g6hj8k9qwertyupzxcvbnm";

mt_srand();

$strs = "";

for ($i = 0; $i < $len; $i ) {

$strs .= $srcstr[mt_rand(0, 30)];

}

return $strs;

}

//随机生成的字符串

$str = random(4);

//验证码图片的宽度

$width = 50;

//验证码图片的高度

$height = 25;

//声明需要创建的图层的图片格式

@ header("Content-Type:image/png");

//创建一个图层

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

//背景色

$back = imagecolorallocate($im, 0xFF, 0xFF, 0xFF);

//模糊点颜色

$pix = imagecolorallocate($im, 187, 230, 247);

//字体色

$font = imagecolorallocate($im, 41, 163, 238);

//绘模糊作用的点

mt_srand();

for ($i = 0; $i < 1000; $i ) {

imagesetpixel($im, mt_rand(0, $width), mt_rand(0, $height), $pix);

}

//输出字符

imagestring($im, 5, 7, 5, $str, $font);

//输出矩形

imagerectangle($im, 0, 0, $width -1, $height -1, $font);

//输出图片

imagepng($im);

imagedestroy($im);

$str = md5($str);

//选择 cookie

//SetCookie("verification", $str, time() 7200, "/");

//选择 Session

$_SESSION["verification"] = $str;

?>

1

2

3

1

4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
<🎜> <🎜> <🎜>session_start();<🎜> <🎜>function random($len) {<🎜> <🎜>$srcstr = "1a2s3d4f5g6hj8k9qwertyupzxcvbnm";<🎜> <🎜>mt_srand();<🎜> <🎜>$strs = "";<🎜> <🎜>for ($i = 0; $i < $len; $i ) {<🎜> <🎜>$strs .= $srcstr[mt_rand(0, 30)];<🎜> <🎜>}<🎜> <🎜>return $strs;<🎜> <🎜>}<🎜> <🎜> <🎜> <🎜>//Randomly generated string<🎜> <🎜>$str = random(4);<🎜> <🎜> <🎜> <🎜>//The width of the verification code image<🎜> <🎜>$width = 50;<🎜> <🎜> <🎜> <🎜>//The height of the verification code image<🎜> <🎜>$height = 25;<🎜> <🎜> <🎜> <🎜>//Declare the image format of the layer to be created<🎜> <🎜>@ header("Content-Type:image/png");<🎜> <🎜> <🎜> <🎜>//Create a layer<🎜> <🎜>$im = imagecreate($width, $height);<🎜> <🎜> <🎜> <🎜>//Background color<🎜> <🎜>$back = imagecolorallocate($im, 0xFF, 0xFF, 0xFF);<🎜> <🎜> <🎜> <🎜>//Blurred point color<🎜> <🎜>$pix = imagecolorallocate($im, 187, 230, 247);<🎜> <🎜> <🎜> <🎜>//Font color<🎜> <🎜>$font = imagecolorallocate($im, 41, 163, 238);<🎜> <🎜> <🎜> <🎜>//Draw the blur effect point<🎜> <🎜>mt_srand();<🎜> <🎜>for ($i = 0; $i < 1000; $i ) {<🎜> <🎜>imagesetpixel($im, mt_rand(0, $width), mt_rand(0, $height), $pix);<🎜> <🎜>}<🎜> <🎜> <🎜> <🎜>//Output characters<🎜> <🎜>imagestring($im, 5, 7, 5, $str, $font);<🎜> <🎜> <🎜> <🎜>//Output rectangle<🎜> <🎜>imagerectangle($im, 0, 0, $width -1, $height -1, $font);<🎜> <🎜> <🎜> <🎜>//Output picture<🎜> <🎜>imagepng($im);<🎜> <🎜> <🎜> <🎜>imagedestroy($im);<🎜> <🎜> <🎜> <🎜>$str = md5($str);<🎜> <🎜> <🎜> <🎜>//Select cookies<🎜> <🎜>//SetCookie("verification", $str, time() 7200, "/");<🎜> <🎜> <🎜> <🎜>//Select Session<🎜> <🎜>$_SESSION["verification"] = $str;<🎜> <🎜>?>
Then just call it on the page:  ?
1

If you want to achieve the "Can't see clearly? Change another" effect, add the following JS to the page

 ?

1

2

3

function changing(){

document.getElementById('checkpic').src="/images/checkcode.php?" Math.random();

}

1

2 3

document.getElementById('checkpic').src="/images/checkcode.php?" Math.random(); }
The above is the entire content of this article, I hope you all like it. http://www.bkjia.com/PHPjc/1013643.html
www.bkjia.com
truehttp: //www.bkjia.com/PHPjc/1013643.htmlTechArticlephp generated image verification code Verification code is very important in WEB applications. It is usually used to prevent users from maliciously submitting forms, such as Malicious registration and login, malicious forum spamming, etc. This article will explain through examples...
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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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

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,

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 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.

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

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.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

See all articles