Home >Backend Development >PHP Tutorial >How to implement PHP algorithm verification code and Chinese character verification code

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

WBOY
WBOYOriginal
2016-07-25 08:45:15933browse

In PHP website development, verification codes can effectively protect our forms from malicious submissions, but if you do not use arithmetic verification codes or Chinese character verification codes, but only use simple alphabetical or numerical verification codes, such a verification code scheme is really is it safe?

Everyone knows that simple numerical or alphabetical verification codes are easy to crack, but arithmetic verification codes or Chinese character verification codes are not easily cracked. 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:

  1. session_start();
  2. header("Content-type: image/png");
  3. $num1 = mt_rand(0,9);// The first digit
  4. $num2 = mt_rand(1,9);//The second digit
  5. $type_str = "+-*";//Method string collection
  6. $type = substr($type_str,rand(0, 2),1);//Random method
  7. $change = mt_rand(1,3);
  8. if($change==1){
  9. $code = "$num1$type$num2=?";
  10. $result = "$verifyCode=$num1$type$num2;";
  11. eval($result);
  12. $_SESSION['authnum_session'] = $verifyCode;
  13. }elseif($change==2){
  14. $result = "$verifyCode =$num1$type$num2;";
  15. eval($result);
  16. $code = $num1.$type."_=".$verifyCode;
  17. $_SESSION['authnum_session'] = $num2;
  18. }elseif ($change==3){
  19. $result = "$verifyCode=$num1$type$num2;";
  20. eval($result);
  21. $code = "_".$type.$num2."=". $verifyCode;
  22. $_SESSION['authnum_session'] = $num1;
  23. }
  24. $im = imagecreate(68,28);
  25. $black = imagecolorallocate($im, 0,0,0);
  26. $white = imagecolorallocate( $im, 255,255,255);
  27. $gray = imagecolorallocate($im, 200,200,200);
  28. $red = imagecolorallocate($im, 255, 0, 0);
  29. imagefill($im,0,0,$white);
  30. imagestring ($im, 5, 10, 8, $code, $black);
  31. for($i=0;$i<70;$i++) {
  32. imagesetpixel($im, mt_rand(0, 58) , mt_rand(0 , 28) , $black);
  33. imagesetpixel($im, mt_rand(0, 58) , mt_rand(0, 28) , $red);
  34. imagesetpixel($im, mt_rand(0, 58) , mt_rand(0, 28 ), $gray);
  35. }
  36. imagepng($im);
  37. imagedestroy($im);
  38. ?>
Copy code

2. Chinese character verification code:

  1. session_start();
  2. $ch_str="The first thing is that when there is a big problem with the main people, we have to use domestic products to divide the lives. For students at lower levels, they can go out to face-to-face meetings and talk about the kind of life-changing revolution. After having many children, they can add small machines to the society and have high-quality long-term party members. The two political, three good, ten wars and non-agricultural issues in the water physics and chemistry struggle have led to a road map for the joint struggle of the former anti-epidemic and other anti-social bodies. The key point of education is to focus on the change of thinking and internal factors, daily profit, pressure, karma, and performance of the whole group. The leader of the solution group, Mi Qun, only knew that the four horses recognized the sub-Wen Tong, but the strips were more grammatical and the leading force flowed into the receiving seat, and the crude oil was released to set up the problem. The local leaders have established a unified system and transferred to the system. You and the West have been re-elected. The general materials have been re-elected. The six types of light show that the safety zone increases every time the wind returns to Nanguang, Lunke, North, and the truck schedule is integrated. Quickly prevent the Shirashi Shidar Field Weaving Calendar Flower to be passed down orally to judge the status of the Naga Realm products and judge the reference layer to stop the border clearing to Wanquan to investigate the technical conditions. The factory must leave the sea and hand over the right, and the young talent certificate is low and crosses the border. The Eight Examination Rules are about to be announced. The iron gate is about to be moved. The county soldiers are solid and the enemy is eliminated. It leads to thousands of victories and fine shadows. Hua Jue's name is red and the medicine mark is difficult to save. It is difficult to save the body. It is appropriate to talk about the value of beauty. Huang Yibiao takes the morning shift. Mai cuts the letter. The sound of the stage should be hit. Zhang Mi harms Houcao. He Shufei follows the city's strict path and snail inspection. Hei Wu Pei Zhu He Di only needles how to plant Beijing to help the king's eye she catches containing seedlings vice miscellaneous talk about surrounding food radioactive sources causing sour old but sufficient short strokes Xuanhuan Luoshou Chibo Chengfen Jianfu fish with examination and engraving Enough for the husband to lose the bag and promote the branches of the bacterium. Zhou's rock guard lifted Qu Chunyuan's super-negative sand seal to replace Taimo's poverty. Yangjiang analyzed Mu Mu Yan Qiu Chao Medical School Gu Ni Dao. Zigu just wrote that Liu Weiluo was a fan of Ah Chuan, a certain skill set friend, a limited item, a rewind, a roll, a law, and a rain, so that Gu Yuan helped Chupi broadcast and dominated the death circle. The top policy of plug steel is double-leaved and the base is sucked and blocked, so the shield is late and the silk is scattered and welded. Pillar Li Wangpan magnetic hero seems to be trapped Gong Yizhou takes off the slave side Rungai swings the touch star loosely and sends the independent official mixed discipline yet to stand up Kuan Dongzhang wet partial pattern eats the executive valve mine village responsibility mature steadily wins the hard price Nufanqi A pre-job review, back-association damage, cotton invasion, ash, although the spear is thick, the mud is in the egg box, the oxygen is in the palm, the love is stopped, the camp is dissolved, the money is exhausted, the Russian shrinks, the sand retreats, the weapon carries the cells, which exploits the spin levy groove. Hold the shoulder upside down, still ah, fresh bar card, rough introduction, chasing weak feet, afraid of salt powder, Yin Feng, printing bees, urgently taking, expanding the wound, exposing the nucleus, vibrating, vibrating, central, Wuyu, very fast, brilliant, out of order, paper-free, night town, Jiuli, cylinder clip, Nian Lanying Gou Yi? Confucianism kills steam, phosphorus, hard crystal, inserts elastin, burns joy, iron supplements, we buds, buds, tiles, slanting irrigation, Europe, presents, pigs, foreign rots, please penetrate the company's dangerous pulse, it is appropriate to smile like a tail beam, strong and violent enterprise cabbage ear In the Chu and Han Dynasties, the green color of dragging cows was dyed, and in the autumn, forged jade was everywhere, and in summer, it was cured and sharpened. Feizhou visited Feizhou, blew the bronze edge, and replaced rolling guests. It summoned drought, enlightened the mind, stimulated the brain, and penetrated the Tibet. Dare to make cracks in the furnace shell. The sulfur coal welcomes the cast and sticks. Explore the thin ten days. Good blessings and gifts are chosen, willing to subdue the remaining thunder and smoke, the sentence is pure, the plowing is running, the swamp is slowly planted, the Lu Chifan realm is crossed, the tide is crossed, the pool is broken, the ship is ruined, the false light is said to be entrusted to the husband, Zhe is pregnant, and the tribute is presented. The wealth and rituals are sinking and refining. Stop the car, wear the goods, sell all the rats, draw pictures, feed the dragon, keep the house, sing the song, Han Xi, wash the waste, accept the belly, record the mirror, the evil fat village, rub the danger, praise the bell, shake the handle, debate the bamboo valley, sell the chaos, the empty bridge, Ober, rush down the road. Wall network intercepts wild remains, plots, hangs classes, suppresses excessive prosperity, endures aid, worries, returns to Fuqing, gathers around, dances in a hurry, encounters cables, Gu Jiaoyang Lake, nails, broken music, stretches out lamps to avoid floods, answers to Yongpinhuang, Liuhajie, Gannuogui Who attacked Xian Nong Island? The bombs poured down the information. The clever eggs closed the children and released the breasts. The private bankers Yi Jingtan tired uniform mold Du Lele separated the results and recruited Hu Hutongfeng. Ling Chaihuangwu jumped to Shangding Qinshao. Chasing beams, breaking consumption, alkali special hills, digging blades, dramas, hehe chests, Hengqin films, posts, seedlings, slow protrusions, scissors, snow chains, fishermen, face households, Lospora Bo League, buying Yang Zongjiao Sai flag, filtering silicon carbon stocks, sitting and steaming Ning Jing was trapped in a gun, Li rescued a criminal in a dark hole, you Song Arc exploded, Tu Wei Jin arm barrier brown land, Jian Zun Douba Mo arrived at Sangpo seam police picked on the ice Cambodian mouth, what kind of rice plastic mail Zhao Ming pad Kang Zunmu was ordered by a garden accent Fragrant meat brother Wu Minhui forgot his clothes, Sun Linling deceived Xiu, borrowed Dandu's ear, shaved tiger's pen, Kunlang Sa tea dripped shallow cunt, covered Lun Niang's sleeves with tons of soaked beads, female mother's purple opera tower hammer shocked her old appearance, clean and cut off the prison, suspected Ba Shanpu fiercely complains about brushing, ruthlessness, sudden disasters, Qiao Tang leaks the news about sinking molten chlorine, barren stems, men who rob the pulp, and sing the praises of the monks, and catch the locks, especially Wu Zhidan, allowing the rebellious livestock prisoners to touch the rust and sweep the glass. Secret net Jiang calcium shoulder Teng dry throw rail hall mix Dad follow the inducement blessing Ken wine rope poor pond dry bubble bag Lang feed aluminum soft canal grain habitual trade excrement comprehensive wall trend toward the other side ink hinder the unloading fog crown Bing street Laibei radiate intestines, pay good fortune, permeate Rui, startle, squeeze seconds, hang mulansen, sugar, holy concave pottery, late silkworms, billion moments";
  3. $len = mb_strlen($ch_str,"utf-8");//Chinese character length
  4. $str = array ();
  5. for($i=0;$i<4;$i++){
  6. $pos = mt_rand(0,$len-5);//Starting position
  7. $str[] = mb_substr($ch_str,$ pos,1,"utf-8");
  8. }
  9. $authnum_session = implode("",$str);
  10. $_SESSION['authnum_session'] = $authnum_session; //Record to session
  11. Header("Content-type: image/PNG");
  12. //The length of the image And high
  13. $image_x=100;
  14. $image_y=50;
  15. $im = imagecreate($image_x,$image_y);
  16. //Here, the background color of the picture is white
  17. $bkg = ImageColorAllocate($im,255,255,255);
  18. //Displayed font style, this requires placing the file in the corresponding directory. If you don't have a file, go to the window font file to find one.
  19. $fnt = "simhei.ttf";
  20. //Assign some colors to the image
  21. $white=ImageColorAllocate($im,234,185,95);
  22. //Draw an elliptical arc on the image, specify the lower coordinate point
  23. imagearc($ im, 150, 8, 20, 20, 75, 170, $white);
  24. imagearc($im, 180, 7,50, 30, 75, 175, $white);
  25. //Draw a line segment on the picture, Specify the lower coordinate point
  26. imageline($im,20,20,180,30,$white);
  27. imageline($im,20,18,170,50,$white);
  28. imageline($im,25,50,80,50, $white);
  29. //The number of random dots
  30. $noise_num=3000;
  31. $line_num=50;
  32. //The colors of various chaotic characters
  33. $rectangle_color=imagecolorallocate($im,0xAA,0xAA,0xAA);
  34. $ noise_color=imagecolorallocate($im,0x00,0x00,0x00);
  35. $font_color=imagecolorallocate($im,0x00,0x00,0x00);
  36. for($i=0;$i<$noise_num;$i++)
  37. {
  38. //Draw a single pixel on a coordinate point. This point is defined above and is black.
  39. //imagesetpixel($im,mt_rand(0,$image_x),mt_rand(0,$image_y),$noise_color);
  40. }
  41. for($i=0;$i<$line_num;$i++)
  42. {
  43. $line_color=imagecolorallocate($im,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
  44. //Draw a line between two coordinate points, the color is defined above
  45. imageline($im,mt_rand(0 ,$image_x),mt_rand(0,$image_y),mt_rand(0,$image_x),mt_rand(0,$image_y),$line_color);
  46. }
  47. for ($i=0;$i<4;$i++ )
  48. {
  49. 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]);
  50. }
  51. ImagePNG($im) ;
  52. ImageDestroy($im);
  53. ?>
Copy code


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.

From: http://www.phpxs.com/post/3083
Verification code, PHP


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
Previous article:php remove html tag codeNext article:php remove html tag code