Home Backend Development PHP Tutorial Multiple examples of php image verification code

Multiple examples of php image verification code

Jul 25, 2016 am 08:52 AM

  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<18;$i++){
  15. / /Get a random light color
  16. $line_color = imagecolorallocate($im,rand(200,255),rand(200,255),rand(200,255));
  17. //Draw a line
  18. imageline($im,2,$i,47,$i, $line_color);
  19. }

  20. //Set the font size

  21. $font_size=12;

  22. //Set the printed text

  23. $Str[0] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  24. $Str[1] = "abcdefghijklmnopqrstuvwxyz";
  25. $Str[2] = "01234567891234567890123456";

  26. //Get the first random text

  27. $imstr[0 ]["s"] = $Str[rand(0,2)][rand(0,25)];
  28. $imstr[0]["x"] = rand(2,5);
  29. $imstr[0 ]["y"] = rand(1,4);

  30. //Get the second random text

  31. $imstr[1]["s"] = $Str[rand(0 ,2)][rand(0,25)];
  32. $imstr[1]["x"] = $imstr[0]["x"]+$font_size-1+rand(0,1);
  33. $ imstr[1]["y"] = rand(1,3);

  34. //Get the 3rd random text

  35. $imstr[2]["s"] = $Str[ rand(0,2)][rand(0,25)];
  36. $imstr[2]["x"] = $imstr[1]["x"]+$font_size-1+rand(0,1) ;
  37. $imstr[2]["y"] = rand(1,4);

  38. //Get the 4th random text

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

  42. //Write random string

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

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

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<$codelen;$i++) {
  17. $authstr .= $charset[mt_rand(0,$_len)];
  18. }
  19. session_start();
  20. $_SESSION['scode']=strtolower($authstr );//Convert all to lowercase, mainly to avoid case sensitivity
  21. //Draw random dots, which have been changed to stars
  22. for ($i=0;$i<$imgwidth;$i++){
  23. $randcolor =imageColorallocate($im,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255));
  24. imagestring($im,mt_rand(1,5), mt_rand(0,$imgwidth),mt_rand(0,$imgheight) , '*',$randcolor);
  25. //imagesetpixel($im,mt_rand(0,$imgwidth),mt_rand(0,$imgheight),$randcolor);
  26. }
  27. //Draw lines randomly, number of lines = characters Quantity (anything)
  28. for($i=0;$i<$codelen;$i++)
  29. {
  30. $randcolor=imagecolorallocate($im,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
  31. imageline ($im,0,mt_rand(0,$imgheight),$imgwidth,mt_rand(0,$imgheight),$randcolor);
  32. }
  33. $_x=intval($imgwidth/$codelen); //Calculate character distance
  34. $_y=intval($imgheight*0.7); //Characters are displayed at 70% of the image
  35. for($i=0;$i $randcolor=imagecolorallocate($im ,mt_rand(0,150),mt_rand(0,150),mt_rand(0,150));
  36. //imagestring($im,5,$j,5,$imgstr[$i],$color3);
  37. // imagettftext ( resource $ image , float $size , float $angle , int $x , int $y , int $color , string $fontfile , string $text )
  38. imagettftext($im,$fontsize,mt_rand(-30,30),$i* $_x+3,$_y,$randcolor,$font,$authstr[$i]);
  39. }
  40. //Generate image
  41. header("content-type:image/PNG");
  42. imagePNG($im);
  43. 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<4; $i++){
  7. $rand.=dechex(rand(1,15)); //Generate a 4-digit random number containing hexadecimal
  8. }
  9. $_SESSION[check_gd]=$rand;
  10. $img=imagecreatetruecolor (100,30); //Create a picture
  11. $bg=imagecolorallocate($img,0,0,0); //The first time the background color is generated
  12. $fc=imagecolorallocate($img,255,255,255); // Generated font color
  13. //Draw lines on the picture
  14. for($i=0;$i<3;$i++){
  15. $te=imagecolorallocate($img,rand(0,255),rand(0,255),rand(0,255 ));
  16. imageline($img,rand(0,15),0,100,30,$te);
  17. }
  18. //Draw some points on the picture
  19. for($i=0;$i<200;$i++){
  20. $te=imagecolorallocate($img,rand(0,255),rand(0,255),rand(0,255));
  21. imagesetpixel($img,rand()%100,rand()%30,$te);
  22. }
  23. //First, convert the text into utf-8 format
  24. //$str=iconv("gb2312","utf-8","Hehehe");
  25. //Add Chinese verification
  26. //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
  27. imagettftext($img,11,10,20, 20,$fc,"simkai.ttf","Hello Hello");
  28. //Write the string in the image
  29. //imagestring($img,rand(1,6),rand(3,70) ,rand(3,16),$rand,$fc);
  30. //Output image
  31. header("Content-type:image/jpeg");
  32. imagejpeg($img);
  33. ?>
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:
Copy code


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)

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 does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

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.

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

See all articles