Example of PHP-based formula verification code and Chinese character verification code

Source: Internet
Author: User
This article mainly introduces the example of PHP implementation of the formula verification code and the Chinese character verification code. This article provides the implementation code directly. if you need it, refer to the PHP website development, the verification code can effectively protect our forms from malicious submission. but if you do not use a formula verification code or a Chinese character verification code, simply use a simple letter or digit verification code, is this verification code solution really safe?

We know that simple numbers or letter verification codes can be easily cracked, but computation verification codes or Chinese character verification codes cannot be cracked. Therefore, we recommend that you use verification codes, try to use the formula verification code or Chinese character verification code.

The following are two types of verification code I have written. For more information, see:

1. formula verification code:

The code is as follows:


<? Php
Session_start ();
Header ("Content-type: image/png ");
$ Num1 = mt_rand (0, 9); // The first digit
$ Num2 = mt_rand (); // second digit
$ Type_str = "+-*"; // method string set
$ 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 );
$ 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 <70; $ 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:


<? Php
Session_start ();
$ Ch_str = "first, when there is a conflict with everyone, the main person will use work hours for them. in this case, when I arrive at the country, he will do the work. for the lower-level students, he will create a ministry. the outsourcers can go to the same industry to say that they are too desperate, and after many sub-accounts, they can go from social networks and small hosts, and also rely on their own power lines. the high volume of electricity, the long party has to go through the real-time and deep-seated methods. zheng Sanhao's ten-day war had no prefix for farming and other anti-body fight routes. the newly opened things were changed from when two or more Tianzi event teams were approved and thought-provoking. guan Dian Yu Zhong his thoughts and in-room because of the day-benefit phase by the pressure officer gas industry on behalf of the whole group number fruit period guide each base or month Mao ran asked than exhibition that it did not see governance I propose five solutions to the forest's rice clusters. I only want four horses to recognize the article, but the article is more grams and the leading public holes are connected to the seat transport and flying crude oil. I am very determined that Shi Qiang is very rare and has gone through a total of direct mission to create another cut nine you take the West holding the total material re-election of the mind to adjust the seven What Mountain Cheng Baibao more see must be really hot Protection Committee the hand-modified management department has already completed the repair and identification of the disease, and the old-light and special-style 6-type secondary security belt shows the completion of each East-increased traffic back to the south-Guang Lao Lun kebei to build a car for the festival to be completed. lianbu class Set No. column temperature installation that is without notice axis research solid color fast anti-Shi Lashi set Dalon field weaving calendar flowers by seeking to pass the mouth broken condition mining fine gold industry products determination parameter layer end side clear to ten OK the book-writing factory must be away from the eyes of the sea, and the children of the Qingcai certificate is lower than the eight test rules, near Note to run the bumen iron should go to the county, the soldiers fixed in addition to the teeth like a thousand wins fine shadows Ji Bai Ge effect push blank configuration knife leaf rate today selected Yangde phone query difference half enemy starting film Shi Xiang Huaxu standby name Red continuous average drug Mark difficult to store tester body tight liquid accurate Jin Jiao wei Weiban Xu broke the technology to eliminate the bottom bed Field trend sense to Shen benhe village structure Photo volume not engaged in sub-grinding fire section calculation according to the value of the United States Huang Yibiao service early shift Mai cut letter row sound the attacker Zhang Mi harm Hou Cao he shufa following the right city strict diameter screw detection left Page anti Su Xian bitter English Fast said bad migration of barabai province Black Wu Pei he Di only pin how to plant Jing Zhu Shengwang eye she grasp containing seedlings sub-Miscellaneous talk about food shot source examples caused by acid old but enough short drag agent Xuan ring falls first ruler wave bearing powder jianfu fish with the test engraved rely on enough full husband loss bag promote branch bureau bacteria Rod week Yan teacher to pick Qu Chunyuan ultra negative sand seal for too model poor reduction Yang Jiang analysis Mu Yan ball Chao Medical School gu death poison circle Wei season training control exciting look called cloud mutual split grain mother trainer plug steel top policy Double Stay mistaken Foundation suck resistance so inch shield late silk female powder welding power plants pro Hospital cold hit wrong scattered business video art destroy version strong room light blood times lack of pct pump check absolutely rich City Chong spray soil simple no column Li wangpan magnetic Xiong like sleepy Yi Zhou off cast to slave side run cover the swing from the touch xingsong to get xingdu official mixed Ji according to not burst frame wide winter seal wet partial grain eat hold valve mine village responsibility cooked stable hard price Nu turn Qijia pre-job evaluation read back co-loss cotton invasion of gray although the spear thick Luo mud open the egg box ops oxygen love stopped once dissolved camp final Gang Meng Qian to do Russia to shrink sand back Chen Fen machinery carrying young which strip, force, spin, sign, slot, hold, bear, fresh, card, drill, weak, foot, fear, salt, Yin, Feng, edit, print, Bee, Rush, escape, search, vibration, run, Yang, Wu, domain, very fast different sequence free paper night Township Jiu licylinder folder Nian Lan Ying gou yi ru kill steam phosphorus Jing plug Yi Huan iron fill Yi Ya ya wing WA tilting array carbon play Wei Fu ya Yong tile oblique irrigation ou Xian shun pig foreign rot please pass the division of dangerous pulse should laugh if the tail bunch of strong and violent enterprises food Sui Chu Han more green drag ox copy dyeing autumn round forging Yu Xia treatment tip colony jing Fei Zhou visits blowing Rong copper along the rolling passenger call drought Wu Zhi nancu Piao Tibet dare to make gap shell sulfur coal Yingzhu stick probe thin late Shanfu longitudinal selection ceremony may Fu residual mine yan sentence pure gradual cultivation run ze slow planting Lu Chifan environment tide off cone Xi Chi defeat ship false Bright said to the gang Zhe Huai cut the tribute was strong financial instrument sinning Ma Sin zuxi car wear goods sales Qi rat pumping painting feeding longku Shouzhu house Song Han Xi brother wash eclipse waste na belly almost recording mirror women evil fat village wipe risk likes bell shake the handle debate Zhugu sell chaos virtual bridge OBO catch the way of the amount of the Wall network cut Wild left quiet seek to get the hanging class town arrogant Sheng aid Zha worry key Fu Qing together around the Moo busy dance met Suo gu Jiao Yanghu dingTalk Renyin trace broken stretch lamp to avoid pan death answer Yong frequency Huang Liu ha uncover ganuo summary Xian concentrated island attack who Hong Xie gun pouring spot news understand spirit egg closed children release milk giant private yin Yi Jing Tan tired Yun Mo Dulle bending performance recruit Shao Hu call pain peak 0 Chai spring Wu jump Ju Shang ding Qin slightly chasing Liang discount alkali Shugang dig blade drama hehe chest heng Qin film published in the case of slow and convex active cut Sichuan snow chain Yu la face households Luo Shu Bo Meng buy Yang zongjiao Saqi filter silicon carbon shares sitting steam condensate actually trapped gun Li rescue hidden holes criminal tube you song arc burst paradox Tu flavor Jin arm barrier Brown Lu Jian Zun bean pull Mo against Sanpo sewing police pick dirty ice Cambodia mouth what Rice plastic sent Zhao shout mat Kang Zumu was Frame garden cavity order fragrant meat younger brother House Min Hui forget clothing Sun Ling lie Hugh borrow Dan du ear planing tiger pen thin Kun Lang SA Tea drop showner cave covered Lun Niang tons dip sleeve beads female mom zixi Tower hammer shock years old appearance clean split prison front suspected BA flash Po fierce v brush malicious and disaster recovery noisy Qiao Tang leak smell Shen Rong chlorine waste stem man where grab like pulp beside Bo also loyal sing Mengyu to catch the lock, especially by the Wuzhi light allow rebellion animal capture touch rust sweep Bibao core Ye Jian secret Jing Jiang calcium shoulder Teng dry throwing rail Hall mix dad follow the temptation to liken liquor rope poor pond dry bubble bag long feed aluminum soft canal used trade dung integrated wall tends to be another ink congestion Qi reverse unload air fog crown C Street laibei spoke sausage Fu Ji Xiaorui stunned squeeze seconds to overhead mu rotten Sen sugar Sheng WA Tao word late silkworm hundred million moment ";
$ Len = mb_strlen ($ ch_str, "UTF-8"); // Chinese character length
$ Str = array ();
For ($ I = 0; $ I <4; $ I ++ ){
$ Pos = mt_rand (0, $ len-5); // start 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 image
$ Image_x = 100;
$ Image_y = 50;
$ Im = imagecreate ($ image_x, $ image_y );
// The background color of the image is white.
$ Bkg = ImageColorAllocate ($ im, 255,255,255 );
// Display the font style. put the file in the corresponding directory. if you do not have any file, find one in the font file of window.
$ Fnt = "simhei. ttf ";
// Assign some color to the image
$ White = ImageColorAllocate ($ im, 234,185, 95 );
// Draw an elliptical arc on the image and specify the coordinate point
Imagearc ($ im, 150, 8, 20, 20, 75,170, $ white );
Imagearc ($ im, 180, 75,175, 30, $ white );
// Draw a line segment on the image and specify the coordinate point
Imageline ($ im, 20, 20, 180,30, $ white );
Imageline ($ im, 20, 18, 170,50, $ white );
Imageline ($ im, 25, 50, 80, 50, $ white );
// Number of random points
$ Noise_num = 3000;
$ Line_num = 50;
// Color of various chaotic 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 <$ noise_num; $ I ++)
{
// Draw a single pixel on a coordinate point, which 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_num; $ I ++)
{
$ Line_color = imagecolorallocate ($ im, mt_rand (0,255), mt_rand (0,255), mt_rand (0,255 ));
// Draw a line between two coordinate points, and 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 <4; $ I ++)
{
ImageTTFText ($ im, rand (100), rand (), rand ($ image_x/4) * $ I + $ image_x/, ($ 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.rar click here to download.

Note:

The Chinese character verification code is executed separately. if you obtain the session, the verification code is inconsistent with the session content. However, when the Chinese character verification code file is referenced in the src attribute of the img label, the session is obtained. in this case, the content of the two is consistent.

Interested friends can further improve this.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.