search
HomeBackend DevelopmentPHP TutorialHow to implement Chinese character verification code and arithmetic verification code in PHP_PHP Tutorial

How to implement Chinese character verification code and algorithm verification code in PHP

This article mainly introduces the method of implementing Chinese character verification code and algorithm verification code in PHP, and analyzes the algorithm verification code with examples. And the implementation skills of Chinese character verification code, which are of great practical value. Friends in need can refer to it

The example in this article describes the method of implementing Chinese character verification code and arithmetic verification code in PHP. Share it with everyone for your reference. The specific analysis is as follows:

Everyone knows that simple number or letter verification codes are easy to crack, but arithmetic verification codes or Chinese character verification codes are not easy to crack,
Therefore, it is recommended that when using verification codes, try to use arithmetic verification codes or Chinese character verification codes.
Below are the two verification code codes I wrote. Friends who are useful can refer to them:

1. Calculation verification code:

The code is as follows:

session_start();
header("Content-type: image/png");
$num1 = mt_rand(0,9);//First digit
$num2 = mt_rand(1,9);//Second digit
$type_str = "+-*";//Method string collection
$type = substr($type_str,rand(0,2),1);//Random method
$change = mt_rand(1,3);
if($change==1){
$code = "$num1$type$num2=?";
$result = "$verifyCode=$num1$type$num2;";
eval($result);
$_SESSION['authnum_session'] = $verifyCode;
}elseif($change==2){
$result = "$verifyCode=$num1$type$num2;";
eval($result);
$code = $num1.$type."_=".$verifyCode;
$_SESSION['authnum_session'] = $num2;
}elseif($change==3){
$result = "$verifyCode=$num1$type$num2;";
eval($result);
$code = "_".$type.$num2."=".$verifyCode;
$_SESSION['authnum_session'] = $num1;
}
$im = imagecreate(68,28);
$black = imagecolorallocate($im, 0,0,0);
$white = imagecolorallocate($im, 255,255,255);
$gray = imagecolorallocate($im, 200,200,200);
$red = imagecolorallocate($im, 255, 0, 0);
imagefill($im,0,0,$white);
imagestring($im, 5, 10, 8, $code, $black);
for($i=0;$i imagesetpixel($im, mt_rand(0, 58) , mt_rand(0, 28) , $black);
imagesetpixel($im, mt_rand(0, 58) , mt_rand(0, 28) , $red);
imagesetpixel($im, mt_rand(0, 58) , mt_rand(0, 28) , $gray);
}
imagepng($im);
imagedestroy($im);
?>

2. Chinese character verification code:

The code is as follows:


session_start();
$ch_str="The first thing is that in the discord, there is a large number of people in the country who need to use domestic products to divide students into students at different ages. Fang Jin's colleagues said in an interview that after the revolution, many children were added to the social network, and the power line of the high-quality long-term party was achieved. The road map of anti-sexuality and anti-body cooperation transforms the content of the new discussion from the current situation of the two talents, such as the corresponding form, thinking, thinking, and practice, to the change of key points, the emphasis on thinking and the internal removal of causes. The daily profit phase is determined by the pressure of the whole group of Qi karma, the fruit period, the level of each base or the monthly hair, then the comparison shows that it is the most external and does not look at the five interpretations of the forest. The head of the rice group only knows four horse recognition However, the article is relatively grammatical and public, leading to the inflow of the receiving seat, and flying crude oil to set up the problem to refer to the construction of the district inspection activity, and many educational decisions have been made. You and Xi Jinping's general information will be re-elected and will be re-elected. Qimoshan Cheng Baibao will see that it is necessary to keep warm and hand over the changes in management. We will repair the symptoms, identify the disease symptoms, and the six types of old light. What are the six types of rehabilitation belts? After finishing the wind, I returned to Nanguang, Lunlun, Kebei, and planned the truck schedule and the work was integrated. The step number was listed, the temperature was installed, and the axis was grinded. The solid color was solid, the speed was reduced, and the Shila Shidaer field was weaved. The calendar flower was requested to be passed on. The oral judgment is collected and the Naga World product is judged and the reference layer is stopped at the border and cleared to Wanquan. The factory must be away from the sea and handed over to the right, and the children's youth talent certificate is low and cross-country. The eight test regulations are not far away. The soldiers are solid, the teeth are eliminated, the teeth are thousands of victors, the fine shadows are Jibai, the effect is set and pushed empty, with the blade rate, the current selection is to raise the virtue, then check the difference, half the enemy, the first film is applied, the sound is collected, the Huajue is named, the red is added, the uniform medicine mark is difficult to save, and the body of the soldier is measured. Tight liquid system, accurate weight angle, dimension reduction board, Xu broken technology, bottom bed field potential end sense, Hecun construction, appearance, non-engagement, Yamo family fire section, suitable value, beautiful appearance, Huang Yibiao, morning shift wheat cutting letter row Taiwan's voice should attack Zhang Mi, harm Houcao, He Shufei, follow the right city's strict path and snail inspection, left page, resist Su Xian's bitter British, quickly say bad move, Heiwu Pei Zhu, Yorbachi Province, only needle, how to plant the capital to help the king's eye She catches the seedlings and vice versa and talks about surrounding food radioactive sources causing sourness and old but sufficient short strokes. Teacher Li Qu Chunyuan Super Negative Sand Sealing Change Taimo Poverty Reduction Yangjiang Analysis Mu Mu Yan Qi Chao Medical School Gu Ni Dao Song Ting Wei Shu Hua Station Another Wei Zi Gu Gang Wrote Liu Weilue Fan Gong A Kuai A Certain Kung Fu Set Friend limit item Yu rewinds and creates law rain, let Gu Yuan help Chupibo to occupy the dead poison circle, Wei Ji training and control stimulates to find Yunhu and cracks grain grain mother training plug steel top policy double to stay wrong foundation sucks and blocks so cun shield late Silk girl scattered welding power Zhu pro-in hospital cold and thorough bombing scattered business visual art destroyed edition Lie zero room light blood times lack of Li pump Cha Juefu city flushing soil Jane Fuzhu Li Wangpan magnetic male seems trapped Gong Yizhou takes off the delivery slave side run cover Swing the distance, touch the star, and send him to the independent official. The discipline has not yet emerged. The wide winter chapter is wet and partial. The boss is responsible for the mine village. The responsibility is mature and the hard price is guaranteed. Nufeng Qijia pre-job evaluation is read. The back is damaged and the cotton is invaded by dust. Although the spear is thick. Luo Nipi sued the egg box, palm oxygen, love, stopped, dissolved camp, ended up with Meng Qian waiting to be exhausted, Russia shrunk, sand retreated, Chen challenged the equipment to carry the young, which exploited the rotary levy slot, held the shoulder, still ah, fresh bar card, rough introduction, drilled and chased the weak foot. Afraid of the end of salt, Yin Feng, compiled by bees, rushed to expand the wound, exposed the core edge, traveled, vibrated, and vibrated in the central five areas, very fast, out of sequence, paper-free, night town, long-term servitude, cylinder clip, read Lan Yinggou B? Make up for the yong tiles, the carbon performance, the teeth, the yong tiles, the oblique irrigation, the European and shun pigs, the foreign rots, please pass through the Si Wei Kuo pulse, it is good to smile, if the tail bunch is strong, the vegetable ears, Chu Han Yu, the green, drag the cattle, dye them all over the autumn, forge the jade summer. Healing the tip of the well, Feizhou, visiting, blowing the bronze edge, calling for rolling guests, summoning the drought, enlightening the mind, piercing the brain, passing through the Tibet, dare to order the gap, the furnace shell, the sulfur coal, welcome the cast and stick, explore the thin ten days, good fortune, indulge in the rituals, wish to subdue the residual thunder, and extend the smoke, pure and gradual Farming, running, slowly planting, Lu Chifan's realm, the tide crossed, Xichi, the ship was destroyed, falsely said, entrusted Huo Zhehuai, cut tribute, presented strong wealth, rituals, heavy refining, sin, ancestors rested, chariots were worn, goods were sold, rats were drawn, dragons were kept, and warehouses were built. Fangge Hanxi, brother washes away the waste and takes in the belly. He records the mirror, the woman is evil, the village wipes the risk, praises the bell, shakes the handle, debates the bamboo valley, sells the chaos, the bridge, Ober, rushes to the vertical road, the forehead wall, cuts off the wild remains, plots, hangs the class, suppresses the madness, and endures. Aid Zha, consider the key, return to Fuqing, gather around the mo, dance in a hurry, encounter the rope, Gu Jiaoyang Lake, nail kernel, broken sound track, stretch out the lamp, avoid flood, die, answer bravely, Huang Liuhajie, Gannuogai, Xian Nong Island, who is attacked by flood, cannon pouring, information, understanding spirit egg Close the child and release the breast, the giant private banker, Yi Jingtan, tired uniform mold, Du Lele, separated by the curve, Zhao Shao, Hu Hutongfeng, Ling Chai Spring Wu, jumped to Shang Ding, Qin Shao, chased the beam, broke the alkali, special hill, dug the blade, drama, hehe chest. The Hengqin film article was published in the case publication. It's ridiculous to paint Wei Jin's arms, brown land, Jianzun Doubamo, Sangpo's sewing police pick on the ice and Cambodian mouth, what kind of rice plastic is sent to Zhao Mingpad, Kang Zunmu, was cheated by the garden-tongued flesh brother Wu Minhui, who forgot his clothes, Sun Linling, cheated and borrowed. Dandu's ears are shaved, tiger's pen is thin, Kunlang Sa's tea drops are shallow, her cunt is covered with Lun Niang's tons of sleeve beads, her mother's purple opera tower is hammered, her appearance is clean, her face is clean, her face is broken, her head is doubtful, her tyrant flashes her face, she complains about her, she is ruthless, and suddenly there is a disaster. Qiao Tang leaks the news. Sinking, melting, chlorine, barren stems, men who snatch the pulp, are loyal, sing, and catch the locks. You take advantage of Wu Zhidan and allow the rebel livestock prisoners to touch the rust and sweep the glass. Zhu Liken wine rope poor pond dry bubble bag Lang feed aluminum soft canal habitual trade excrement comprehensive wall tend to the other side ink hinder the opening and reverse unloading fog crown Bing street Lebei radiation intestines Fu Ji see Rui startled squeeze seconds hanging mu rotten forest "Tang Sheng's concave pottery poem Chi Can Yi Ju";
$len = mb_strlen($ch_str,"utf-8");//Chinese character length
$str = array();
for($i=0;$i $pos = mt_rand(0,$len-5);//Starting position
$str[] = mb_substr($ch_str,$pos,1,"utf-8");
}
$authnum_session = implode("",$str);
$_SESSION['authnum_session'] = $authnum_session; //Record to session
Header("Content-type: image/PNG");
//The length and height of the picture
$image_x=100;
$image_y=50;
$im = imagecreate($image_x,$image_y);
//The background color of the picture here is white
$bkg = ImageColorAllocate($im,255,255,255);
//Displayed font style, this requires placing the file in the corresponding directory. If you don't have a file, go find one in the window's font file.
$fnt = "simhei.ttf";
//Assign some color to the image
$white=ImageColorAllocate($im,234,185,95);
//Draw an elliptical arc on the picture and specify the lower coordinate point
imagearc($im, 150, 8, 20, 20, 75, 170, $white);
imagearc($im, 180, 7,50, 30, 75, 175, $white);
//Draw a line segment on the picture and specify the lower coordinate point
imageline($im,20,20,180,30,$white);
imageline($im,20,18,170,50,$white);
imageline($im,25,50,80,50,$white);
//The number of random points
$noise_num=3000;
$line_num=50;
//Color of various confusing characters
$rectangle_color=imagecolorallocate($im,0xAA,0xAA,0xAA);
$noise_color=imagecolorallocate($im,0x00,0x00,0x00);
$font_color=imagecolorallocate($im,0x00,0x00,0x00);
for($i=0;$i {
//Draw a single pixel on a coordinate point. This point is defined above and is black.
//imagesetpixel($im,mt_rand(0,$image_x),mt_rand(0,$image_y),$noise_color);
}
for($i=0;$i {
$line_color=imagecolorallocate($im,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
//Draw a line between two coordinate points, the color is defined above
imageline($im,mt_rand(0,$image_x),mt_rand(0,$image_y),mt_rand(0,$image_x),mt_rand(0,$image_y),$line_color);
}

for ($i=0;$i {
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]);

}
ImagePNG($im);
ImageDestroy($im);
?>

Font file: simhei.rarClick here to download from this site.

Note:

The Chinese character verification code is executed separately, and then when you get the session, you will find 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.
Interested friends can further improve this.

I hope this article will be helpful to everyone’s PHP programming design.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/963968.htmlTechArticleHow to implement Chinese character verification code and algorithm verification code in PHP. This article mainly introduces the method of implementing Chinese character verification code and algorithm in PHP. Verification code method, example analysis of algorithm verification code and Chinese character verification...
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

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.

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

Video Face Swap

Video Face Swap

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

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools