Home Backend Development PHP Tutorial PHP implements Chinese character verification code and arithmetic verification code

PHP implements Chinese character verification code and arithmetic verification code

Jul 25, 2016 am 08:44 AM

  1. Everyone knows that simple numerical or letter verification codes are easy to crack, but arithmetic verification codes or Chinese character verification codes are not easy to be cracked,
  2. So it is recommended that when using verification codes, try to use arithmetic verification codes or Chinese character verification code.
  3. Below are the two verification code codes I wrote. Friends who are useful can refer to them:
  4. 1. Calculation verification code:
  5. session_start();
  6. header("Content-type: image/png ");
  7. $num1 = mt_rand(0,9);//The first digit
  8. $num2 = mt_rand(1,9);//The second digit
  9. $type_str = "+-*";/ /Method string collection
  10. $type = substr($type_str,rand(0,2),1);//Random method
  11. $change = mt_rand(1,3);
  12. if($change==1) {
  13. $code = "$num1$type$num2=?";
  14. $result = "\$verifyCode=$num1$type$num2;";
  15. eval($result);
  16. $_SESSION['authnum_session'] = $verifyCode;
  17. }elseif($change==2){
  18. $result = "\$verifyCode=$num1$type$num2;";
  19. eval($result);
  20. $code = $num1.$type. "_=".$verifyCode;
  21. $_SESSION['authnum_session'] = $num2;
  22. }elseif($change==3){
  23. $result = "\$verifyCode=$num1$type$num2;";
  24. eval($result);
  25. $code = "_".$type.$num2."=".$verifyCode;
  26. $_SESSION['authnum_session'] = $num1;
  27. }
  28. $im = imagecreate (68,28);
  29. $black = imagecolorallocate($im, 0,0,0);
  30. $white = imagecolorallocate($im, 255,255,255);
  31. $gray = imagecolorallocate($im, 200,200,200);
  32. $red = imagecolorallocate($im, 255, 0, 0);
  33. imagefill($im,0,0,$white);
  34. imagestring($im, 5, 10, 8, $code, $black);
  35. for( $i=0;$i<70;$i++) {
  36. imagesetpixel($im, mt_rand(0, 58) , mt_rand(0, 28) , $black);
  37. imagesetpixel($im, mt_rand(0, 58) , mt_rand(0, 28) , $red);
  38. imagesetpixel($im, mt_rand(0, 58) , mt_rand(0, 28) , $gray);
  39. }
  40. imagepng($im);
  41. imagedestroy($im);
  42. ?>
  43. 2. Chinese character verification code:
  44. session_start();
  45. $ch_str="The one is in discord There is a large number of people in the country who need to use domestic products to divide students into students at lower levels for the sake of their employment, so that they can carry out this kind of transitional revolution. After many children, the society has added small machines and has experienced high-quality and long-term power. The newly discussed things in this article start from the following two aspects: the talent, the team, the team, the form, the thinking, the mentality, the work, the changes, the key points, the thinking and the time, the factors, the benefits, the pressure, the behavior, and the whole The number of groups in the fruit period leads to the level of each base or the hair of the month. However, the comparison shows that it is the most external and does not look at the management of the five solutions of the forest. The Mi group head means only the four horses recognize the sub-text but the strip is more grams and the public hole leads the inflow. Taking over the seat situation and flying crude oil placement issues pointed out that the district construction inspection activity has been very educational and decision-making. Chang Shiqiang, the Prime Minister, has established a unified system and transferred to the Communist Party of China. What's more, Cheng Baibao has seen that he must really keep heat and entrust his hands to change the management. He will repair the branches to identify the disease elephants, the old light specializes in six types, and shows that the recovery belt will increase every time. The work of the car plan is integrated and the step number is listed. The temperature is installed and the axis is grinded. The solid color is solid and the speed is high. From the border to the Qing Dynasty, the official research factory must leave the sea and hand over the power again, and the children's youth talent certificate is low and crosses the eight examination regulations. The gate is not far away and the iron gate needs to be discussed. White grid effect setting push empty with knife leaf rate report today choose Yangde words check half enemy first tablet Shi Xiangshou Huajue prepared name red continued average medicine mark difficult to save tester body tight liquid faction accurate weight angle dimension reduction board Xu broken The technique is used to eliminate the potential of the bottom bed, and the sense of going to God is convenient. The tree fertilizer follows the right city's strict snail inspection, the left page resists the Soviet Union, the bitter British quickly call the bad move, the Heiwu Pei Zhu River Emperor of Yorba Cai Province, only the needle, how to plant the capital to help the king's eye, she grasps the seedlings, the deputy miscellaneous general talks about the food shot. The source example is acid-causing old but sufficient shorting agent. Model Poverty Alleviation Yang Yangjiang Analyze Mu Yan Qiu Chao Medical School Gu Dao Song Ting Wei Shu Sliding Station Another Wei Zi Gu Gang Wrote Liu Wei Lue Fan Gong A Block A Certain Gong Tao You Limited Item I Rewinded Volume Creation Lv Yu Let Gu Yuanbang Chupi Bo Youzhan Wei Ji Training and Control Exciting Calling Cloud Mutual and Cracking Grain Grain Mother Practice Plug Steel Top Policy Double Leaving Mistaken Foundation Suction Blocking So Cun Shield Late Silk Female Dispersion Welding Gong Zhuqin Hospital Leng Cheb The miscellaneous business vision art destroys the version of the fierce zero room light blood times the lack of Li Pump Cha Jue Fu City rushes into the ground Jian Fuzhu Li Wangpan magnetic hero seems to be trapped Gong Yizhou takes off the slave side Run Gai swings the distance and touches the star loosely to send the independent official mixed Ji Yiwei suddenly framed the wide winter chapter, wet partial pattern, eating the executive valve, mining village, responsible, mature, stable, hard price, Nufan Qijia, pre-job review, back cooperation, damage to cotton, dust infestation, although the spear was thick, Luo Mu filed a lawsuit against the egg box, palm oxygen, love, and stopped. The solution camp is finally running out. The money is waiting to be exhausted. The Russian shrinkage sand retreats. Injury, dew, core edge, travel, vibration, central Wu domain, very rapid brilliance, heterogeneous order, paper-free, night town, Jiuli cylinder clip, read Lan Yinggou B? Yaya Yongwa oblique irrigation Ou Xian Shun pig foreign rot please see through Si Wei Kuo pulse should smile like a tail bundle strong violent enterprise cabbage ear Chu Han healed green drag cattle dye both autumn all over forging jade summer treatment tip breeding well Feizhou visit blowing Rong copper edge Summoning drought for rolling guests, enlightening the brain, stabbing the brain, piercing the Tibet, dare to order the cracks in the furnace shell, the sulfur coal welcomes the casting and sticks, explores the thin ten-day period, good fortune, indulges in the choice of etiquette, willing to subdue the residual thunder, extend the smoke, the sentence is pure, gradually plowing, running through the swamp, slowly planting, Lu Chi, flourishing, the tide is horizontal. Drop a cone, Xichi, destroy a ship, pretend to be bright, ask for help, Zhehuai, cut tribute, show strength, wealth, ritual, sin, ancestors rest, wear cars, sell goods, draw rats, draw dragons, storehouses, build houses, sing Hanxi brother, wash away the waste, accept the belly. Recording woman evil fat village rubs danger praise bell shakes code handle debates bamboo valley sells chaos virtual bridge Ober rushes down the road Ebi net intercepts wild legacy quietly plots hangs class town prosperous endurance worries key returns Fu Qing gathers around the horse dances to meet Suo Gu Jiaoyang Lake nail kernel sound track broken stretch lamp to avoid flood death answer Yongfeng Huang Liu Hajie Gan Nuo Gui Xian Nong Island attack Lei Yun mold, Du Lele, separated by bends, Zhao Shao, Hu Hu, Tong Feng, Ling Chai, Spring Wu, jumped to Shang Ding, Qin Shao, chased Liang, lost alkali, dug up the blade, played piles, he chest, Heng Qin, film, published in the case, Yang slowly protruded. Yi Jian Sichuan Snow Chain Fishing Face Hu Luofubo League Buy Yang Zongjiao Saiqi Filter Silicon Carbon Stock Sitting Steaming Condensation Actually Falling into the Gun Li Rescue Risking a Dark Cave and Offending the Tube You Song Arc Explosive Tu Weijin Arm Barrier Brown Land Ah Jianzun Bean Pat Mo arrived at Sangpo, and the police found out about the ice and Cambodian mouth. What kind of rice and plastics were sent to Zhao Shouting? Drops of shallow cunts covered Lun Niang's sleeves soaked with beads, female mother's purple opera tower, hammer shocked, beautiful and clean, front of prison, suspected tyrant flashing, fierce complaint, brushing, cruel, sudden disaster, Qiao Tang leaked, sinking, melting chlorine, barren stem, man snatching next to the pulp Bo Yizhong sings, Meng Yu catches the lock, especially rides on Wu Zhidan, allows the rebellious livestock captives to touch the rust, sweep the glass, treasure core, master, secret clean, Jiang Calcium shoulder, Teng dry, throw rail hall, mix dad, follow the temptation, bless, encourage, wine rope, poor pond, dry bubble bag, Lang Feeding aluminum soft canal grains, customary trade, dung comprehensive wall, trending towards the other side, ink blocking, reverse unloading, fog crown, Bing Street, Lebei radiation intestines, Fu Ji, Rui, startled, squeezed, hanging, mulansen, sugar, holy concave pottery, late silkworm, billion moment";
  46. $len = mb_strlen($ch_str,"utf-8");//Chinese character length
  47. $str = array();
  48. for($i=0;$i<4;$i++){
  49. $pos = mt_rand(0,$len-5);//Starting position
  50. $str[] = mb_substr($ch_str,$pos,1,"utf-8");
  51. }
  52. $authnum_session = implode("",$str);
  53. $_SESSION['authnum_session'] = $authnum_session; //Record to session
  54. Header("Content-type: image/PNG");
  55. //Picture The length and height
  56. $image_x=100;
  57. $image_y=50;
  58. $im = imagecreate($image_x,$image_y);
  59. //The background color of the picture here is white
  60. $bkg = ImageColorAllocate($im,255,255,255) ;
  61. //Displayed font style, this requires placing the file in the corresponding directory. If you don’t have a file, go find one in the font file of the window.
  62. $fnt = "simhei.ttf";
  63. //Assign some colors to the image
  64. $white=ImageColorAllocate($im,234,185,95);
  65. //Draw an elliptical arc on the image, specify the lower coordinate point
  66. imagearc($ im, 150, 8, 20, 20, 75, 170, $white);
  67. imagearc($im, 180, 7,50, 30, 75, 175, $white);
  68. //Draw a line segment on the picture, Specify the lower coordinate point
  69. imageline($im,20,20,180,30,$white);
  70. imageline($im,20,18,170,50,$white);
  71. imageline($im,25,50,80,50, $white);
  72. //The number of random dots
  73. $noise_num=3000;
  74. $line_num=50;
  75. //The colors of various chaotic characters
  76. $rectangle_color=imagecolorallocate($im,0xAA,0xAA,0xAA);
  77. $ noise_color=imagecolorallocate($im,0x00,0x00,0x00);
  78. $font_color=imagecolorallocate($im,0x00,0x00,0x00);
  79. for($i=0;$i<$noise_num;$i++)
  80. {
  81. //Draw a single pixel on a coordinate point. This point is defined above and is black.
  82. //imagesetpixel($im,mt_rand(0,$image_x),mt_rand(0,$image_y),$noise_color);
  83. }
  84. for($i=0;$i<$line_num;$i++)
  85. {
  86. $line_color=imagecolorallocate($im,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
  87. //Draw a line between two coordinate points, the color is defined above
  88. imageline($im,mt_rand( 0,$image_x),mt_rand(0,$image_y),mt_rand(0,$image_x),mt_rand(0,$image_y),$line_color);
  89. }
  90. for ($i=0;$i<4; $i++)
  91. {
  92. ImageTTFText($im, rand(18,20), rand(0,20), rand(($image_x/4)*$i+$image_x/100,($image_x/4)*$i+ $image_x/8), rand($image_y/2+$image_y/10,$image_y/2+$image_y/5), $font_color, $fnt, $str[$i]);
  93. }
  94. ImagePNG( $im);
  95. ImageDestroy($im);
  96. ?>
  97. Attached font file: simhei.rar http://www.phpskill.com/uploadfile/file/20141229/simhei2.rar
  98. Note:
  99. The Chinese character verification code is executed separately, and then when the session is obtained, it will be found that the verification code and the session content are inconsistent. But when the Chinese character verification code file is referenced in the src attribute in the img tag, and then the session is obtained, the contents of the two are consistent.
Copy code

Verification code, PHP


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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1272
29
C# Tutorial
1252
24
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 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 in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

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

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.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles