search
HomeBackend DevelopmentPHP TutorialMultiple examples of php image verification code

  1. //File header...

  2. header("Content-type: image/png");
  3. //Create true color white paper
  4. $im = @imagecreatetruecolor (50, 20) or die("Failed to create image");
  5. //Get the background color
  6. $background_color = imagecolorallocate($im, 255, 255, 255);
  7. //Fill the background color (this thing is similar to an oil barrel)
  8. imagefill($im,0,0,$background_color);
  9. //Get the border color
  10. $border_color = imagecolorallocate($im,200,200,200);
  11. //Draw a rectangle, border color 200,200,200
  12. imagerectangle($im,0,0 ,49,19,$border_color);
  13. //Show off the background line by line, use 1 or 0 for full screen

  14. for($i=2;$i / /Get a random light color
  15. $line_color = imagecolorallocate($im,rand(200,255),rand(200,255),rand(200,255));
  16. //Draw a line
  17. imageline($im,2,$i,47,$i, $line_color);
  18. }
  19. //Set the font size

  20. $font_size=12;
  21. //Set the printed text

  22. $Str[0] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  23. $Str[1] = "abcdefghijklmnopqrstuvwxyz";
  24. $Str[2] = "01234567891234567890123456";
  25. //Get the first random text

  26. $imstr[0 ]["s"] = $Str[rand(0,2)][rand(0,25)];
  27. $imstr[0]["x"] = rand(2,5);
  28. $imstr[0 ]["y"] = rand(1,4);
  29. //Get the second random text

  30. $imstr[1]["s"] = $Str[rand(0 ,2)][rand(0,25)];
  31. $imstr[1]["x"] = $imstr[0]["x"]+$font_size-1+rand(0,1);
  32. $ imstr[1]["y"] = rand(1,3);
  33. //Get the 3rd random text

  34. $imstr[2]["s"] = $Str[ rand(0,2)][rand(0,25)];
  35. $imstr[2]["x"] = $imstr[1]["x"]+$font_size-1+rand(0,1) ;
  36. $imstr[2]["y"] = rand(1,4);
  37. //Get the 4th random text

  38. $imstr[3]["s"] = $Str[rand(0,2)][rand(0,25)];
  39. $imstr[3]["x"] = $imstr[2]["x"]+$font_size-1+rand(0 ,1);
  40. $imstr[3]["y"] = rand(1,3);
  41. //Write random string

  42. for($i=0;$i< ;4;$i++){
  43. //Get a random darker color
  44. $text_color = imagecolorallocate($im,rand(50,180),rand(50,180),rand(50,180));
  45. //Draw text
  46. imagechar($im ,$font_size,$imstr[$i]["x"],$imstr[$i]["y"],$imstr[$i]["s"],$text_color);
  47. }> ;
  48. //Display image

  49. imagepng($im);
  50. //Destroy image
  51. imagedestroy($im);
  52. ?>
Copy code

Example 2, beautiful PHP image verification code example Complete code:

  1. /*
  2. * @Author fy
  3. */
  4. $imgwidth =100; //Picture width
  5. $imgheight =40; //Picture height
  6. $codelen =4; //Verification code length
  7. $fontsize =20; //Font size
  8. $charset = 'abcdefghkmnprstuvwxyzABCDEFGHKMNPRSTUVWXYZ23456789';
  9. $font = 'Fonts/segoesc.ttf';
  10. $im=imagecreatetruecolor($imgwidth,$imgheight);
  11. $while=imageColorAllocate($im,255,25 5,255 );
  12. imagefill($im,0,0,$while); //Fill the image
  13. //Get the string
  14. $authstr='';
  15. $_len = strlen($charset)-1;
  16. for ($i =0;$i $authstr .= $charset[mt_rand(0,$_len)];
  17. }
  18. session_start();
  19. $_SESSION['scode']=strtolower($authstr );//Convert all to lowercase, mainly to avoid case sensitivity
  20. //Draw random dots, which have been changed to stars
  21. for ($i=0;$i $randcolor =imageColorallocate($im,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255));
  22. imagestring($im,mt_rand(1,5), mt_rand(0,$imgwidth),mt_rand(0,$imgheight) , '*',$randcolor);
  23. //imagesetpixel($im,mt_rand(0,$imgwidth),mt_rand(0,$imgheight),$randcolor);
  24. }
  25. //Draw lines randomly, number of lines = characters Quantity (anything)
  26. for($i=0;$i{
  27. $randcolor=imagecolorallocate($im,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
  28. imageline ($im,0,mt_rand(0,$imgheight),$imgwidth,mt_rand(0,$imgheight),$randcolor);
  29. }
  30. $_x=intval($imgwidth/$codelen); //Calculate character distance
  31. $_y=intval($imgheight*0.7); //Characters are displayed at 70% of the image
  32. for($i=0;$i $randcolor=imagecolorallocate($im ,mt_rand(0,150),mt_rand(0,150),mt_rand(0,150));
  33. //imagestring($im,5,$j,5,$imgstr[$i],$color3);
  34. // imagettftext ( resource $ image , float $size , float $angle , int $x , int $y , int $color , string $fontfile , string $text )
  35. imagettftext($im,$fontsize,mt_rand(-30,30),$i* $_x+3,$_y,$randcolor,$font,$authstr[$i]);
  36. }
  37. //Generate image
  38. header("content-type:image/PNG");
  39. imagePNG($im);
  40. imageDestroy($im);
Copy code

Example 3, php5 image verification code example code

Example of php5 generating image verification code.

You need to use php GD library function: 1,imagecreatetruecolor-----Create a true color image imagecreatetruecolor(int x_size,int y_size) //x represents width, y represents height 2. imagecolorallocate assigns colors (palette) to an image imagecolorallocate(resource image,int red,int green,int blue)//red,green,blue----three primary colors 3. imagestring drawing function iamgestring(resource image,font,int x,int y,content,color); 4. Output function PHP's header is an action that defines the header. PHP5 supports 3 types: 1,Content-type: xxxx/yyyy 2,Location:xxxx:yyyy/zzzz 3,Status: nnn xxxxxx xxxx/yyyy indicates the type of content file Such as: image/gif image/jpeg image/png Example: header("Content-type:image/jpeg") There are corresponding image types in the GD library imagejpeg(),imagegif(),imagepang() 5.imageline line drawing function iamgeline(resource image,int x1,int y1,int x2,int y2,int color); image ---picture x1 ---starting coordinates y1 x2 ---end point coordinates y2 6.imagesetpixel drawing point function imagesetpixel(resource image,int x,int y,int color) 7.imagettftext writing function with font imagettftext(resource image,float size,float angle,int x,int y,int color,string fontfile,string text) 8. How to insert Chinese php verification code iconv("gb2312","utf-8","string"); //First convert the text into utf-8 format 9. Random function 1, rand([int min,int max]) //rand(1,4) generates numbers from 1 to 4 2, dechex (decimal number) //Convert to hexadecimal

Steps to generate verification code: Generate random numbers -- create pictures -- write random numbers into pictures -- save in session

Enter verification code example gdchek.php

  1. /*
  2. * Generate image verification code
  3. * and open the template in the editor.
  4. */
  5. session_start();
  6. for($i=0;$i$rand.=dechex(rand(1,15)); //Generate a 4-digit random number containing hexadecimal
  7. }
  8. $_SESSION[check_gd]=$rand;
  9. $img=imagecreatetruecolor (100,30); //Create a picture
  10. $bg=imagecolorallocate($img,0,0,0); //The first time the background color is generated
  11. $fc=imagecolorallocate($img,255,255,255); // Generated font color
  12. //Draw lines on the picture
  13. for($i=0;$i$te=imagecolorallocate($img,rand(0,255),rand(0,255),rand(0,255 ));
  14. imageline($img,rand(0,15),0,100,30,$te);
  15. }
  16. //Draw some points on the picture
  17. for($i=0;$i$te=imagecolorallocate($img,rand(0,255),rand(0,255),rand(0,255));
  18. imagesetpixel($img,rand()%100,rand()%30,$te);
  19. }
  20. //First, convert the text into utf-8 format
  21. //$str=iconv("gb2312","utf-8","Hehehe");
  22. //Add Chinese verification
  23. //smkai.ttf is In order to use a font file as a font on other people’s computers, put the file in the root directory of the project and download it. There is also
  24. imagettftext($img,11,10,20, 20,$fc,"simkai.ttf","Hello Hello");
  25. //Write the string in the image
  26. //imagestring($img,rand(1,6),rand(3,70) ,rand(3,16),$rand,$fc);
  27. //Output image
  28. header("Content-type:image/jpeg");
  29. imagejpeg($img);
  30. ?>
Copy code

login.php

  1. /*
  2. *
  3. *
  4. */
  5. session_start();
  6. if($_POST[sub]){
  7. //Judge whether the verification code is the same
  8. if($_POST[gd_pic ]==$_SESSION[check_gd]){
  9. echo "Verification successful!";
  10. }else{
  11. echo "Verification code error";
  12. }
  13. }
  14. ?>
  15. Username:
  16. Password: < ;br>
  17. Verification code:Multiple examples of php image verification code
Copy code


Statement
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
How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Apr 17, 2025 am 12:22 AM

Key players in HTTP cache headers include Cache-Control, ETag, and Last-Modified. 1.Cache-Control is used to control caching policies. Example: Cache-Control:max-age=3600,public. 2. ETag verifies resource changes through unique identifiers, example: ETag: "686897696a7c876b7e". 3.Last-Modified indicates the resource's last modification time, example: Last-Modified:Wed,21Oct201507:28:00GMT.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP: An Introduction to the Server-Side Scripting LanguagePHP: An Introduction to the Server-Side Scripting LanguageApr 16, 2025 am 12:18 AM

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP and the Web: Exploring its Long-Term ImpactPHP and the Web: Exploring its Long-Term ImpactApr 16, 2025 am 12:17 AM

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

Why Use PHP? Advantages and Benefits ExplainedWhy Use PHP? Advantages and Benefits ExplainedApr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

See all articles

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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft