PHP Implementation Formula Verification code and Chinese character Verification code example, PHP code example _php Tutorial

Source: Internet
Author: User
Tags php code examples

PHP implementation of the formula verification Code and Chinese character Verification code example, PHP formula code example


In the development of PHP Web site, verification code can effectively protect our forms from malicious submissions, but if you do not use the Formula verification code or Chinese character verification code, just use simple letters or digital verification code, such a verification code scheme is really safe?

We know that simple numbers or letter verification code is easy to be cracked, but the formula verification code or Chinese character verification code is not easy to be cracked, so we recommend that you use the verification code, as far as possible with the formula verification code or Chinese character verification code.

Here are the two codes I wrote, useful to friends can refer to the following:

1. Formula Verification Code:
Copy CodeThe code is as follows:
<?php
Session_Start ();
Header ("Content-type:image/png");
$num 1 = mt_rand (0,9);//First digit
$num 2 = 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 = "$num 1$type$num2=?";
$result = "$verifyCode = $num 1$type$num2;";
eval ($result);
$_session[' authnum_session '] = $verifyCode;
}elseif ($change ==2) {
$result = "$verifyCode = $num 1$type$num2;";
eval ($result);
$code = $num 1. $type. " _= ". $verifyCode;
$_session[' authnum_session '] = $num 2;
}elseif ($change ==3) {
$result = "$verifyCode = $num 1$type$num2;";
eval ($result);
$code = "_". $type. $num 2. " = ". $verifyCode;
$_session[' authnum_session '] = $num 1;
}
$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, 8, $code, $black);
for ($i =0; $i <70; $i + +) {
Imagesetpixel ($im, Mt_rand (0), Mt_rand (0,), $black);
Imagesetpixel ($im, Mt_rand (0), Mt_rand (0,), $red);
Imagesetpixel ($im, Mt_rand (0), Mt_rand (0,), $gray);
}
Imagepng ($im);
Imagedestroy ($im);
?>

2. Chinese Character Verification Code:
Copy CodeThe code is as follows:
<?php
Session_Start ();
$ch _str= " The first is in the big and the main person for the people on the labor to move to the domestic with me to he will be a sub-class on the level of the level of righteousness to the Ministry of the public can be out of the side of the peer said to grow a life of leather and many children after self-social plus small machine also through the power line of the high-volume long party to real home fixed deep method of water physical and chemical dispute is two from the Miyoshi 10 war, non-agricultural and other anti-body road map to the new opening of the knot in the first Things from when the two also gifted team, such as should shape want to make a heart-like dry all to change the point of fertility and the inner part of the cause of the day by the pressure of the members of the gas industry on behalf of the whole group number of fruit phase guide the basis or month Mao ran it's the most and the outside. Five solutions to the forest of the Mi Qun head meaning only Ming four Ma Wen Tong, but the bar and the male hole leader inflow into the seat of the EQ and fly crude oil put up the problem of quality refers to the establishment of the area to test the living people are very teaching Hereby, often stone strong soil less has root of the total alignment of the general type of conversion nine you take the west holding the total material re-election of the concept of seven, the mountain-pass hundred more see must be true to protect the Heat committee hand to the branch has been to repair the heath a few first avoid special what type six with an indication of the return of each east of the wind back to the south-canton of the north of the road to make a car to do business by the whole set number of Levin installed, namely, the unknown axis research monochrome solid-fast anti-Slavs set up the field weaving calendar Flowers by To find out the fault condition of mining fine gold boundary products to the boundary clearance to million accurate book operation factory must be away from the re-head of the sea-right vote children green only certificate of low cross-border eight test regulation of the near-to-the-gate iron need to go to the county soldiers solid removal of the same as the lead teeth thousand wins a brief review on the leaf rate of the white lattice effect of the fine shadow in the selection of the blade ratio of the current election to the second half of the enemy began to apply sound to the recovery of the name of the red continuation of the drug mark is difficult to keep the weight of the body tight liquid of the lower dimension plate of the reduction of the base bed field Potential end sense toward God he cun structure illumination capacity not to engage in the sub-mill Group fire Section calculation of the state-of-the-Huang clothing morning wheat cutting letter row station sound of the hit Su Zhangmi hou Cao He tree fertilizer in the right side of the city of the left page anti-su show bitter British fast called bad move about Pakistan Timber Province black Wuppe Hati only needle How to implant the King eye she grabbed the side of the seedling to talk about the source of the surrounding food injection of acid old but sufficient short-stroke Xuan fall The first ruler wave bearing powder to practice the fish with the test The Mitsuo is enough to lose the pack to promote the branch of the stem Zhou Yan Division Cuschun Ultra-negative sand seal change too mold poverty reduction Yangyangiang analysis mu wood words ball toward medical school ancient rice song listen to the only to lose slip station Another Wei drum just write Liu Weilio fan for a piece of work a set of friends to limit the rest of the roll of law rain let bone far to help the first skin broadcast gifted death poison Circle Wei Ti Xun control excited to call the cloud mutual crack grain masterbatch Female practice plug steel top strategy double left wrong base suction resistance so inch shield late silk woman loose welding gong Plant Pro-school cold and wrong scattered commercial visual arts and crafts out of the 0 room light blood times the lack of the pump observation of the urban Chong-tu-tu soil simply no column Li Huanpan magnetic male like trapped Shong off delivery slave side run cover swing from the touch star Pine to receive the independence of the official mixed Ji Yi the width of the winter chapter of the wet partial grain to eat and hold the valve mine village responsibility mature steady win hard price to turn odd a pre-vocational evaluation read Back association damage cotton invasion Ash although spear thick Luo mud to inform egg box palm oxygen loving stop once dissolve camp finally outline Meng money to be full of Russian shrinkage Sha Hui Chen to beg for the child of the force of the small stripping of the rotation of the groove down to hold it still ah fresh bar card coarse medium drill weak foot afraid of salt end Yin Feng Production Bee urgent take the expansion of flying dew nuclear margin Rang Central Wu-Hui, non-paper night township long scribe cylinder clip read LAN Anh Ditch b Confucianism kill vapor phosphorus difficult crystal plug the Flame Huan iron complement our Bud Yongwa Dip array Carbon show Wei tooth Bud Yong wa Oblique irrigation Eugeshun Pig Yang Rot please the meridian of the pulse should laugh if the tail of the strong and the enterprise dish The Han and the green drag the cattle to dye the autumn-time forging jade summer treatment of the Kinguizhou to blow Rong BronzeFollow the roller to call the dry understanding thorn brain measure the penetration of the furnace shell sulfur coal ying casting sticking to the light of the good fortune of the Reyen the residual smoke sentence pure gradually tillage run ze slow planting Rutch prosperity cross-cut cone Hitch defeat ship false bright predicate Zhehwai cutting pendulum tribute to the Jin-fu-Lian ma sin ancestral car wear cargo pin Zimping draw feed Dragon Storehouse keep build room song Cold Xi elder brother wash eclipse waste na abdomen by the record mirror women's fat zhuang rub risk praise bell swing handle Bamboo Valley sell Chaos Bridge Ober drive down the wall of the network cross-section of the plot to hang up the town of the road to the Fu Qing of the resistance to the bond of the busy dance encounter So Gu gum yanghu nail benevolence sound trace broken extension lamp to avoid flooding the Emperor Liuha revealed Gannon almost the constitution the island hit who Honche cannon spot understanding Spirit egg closed children release milk giant private silver Ychintan tired mold Dulle isolation bending performance recruit Shaoxing Hu call Pain Peak 0 Diesel Spring noon Jump Ju Shang Dingqin slightly chase beam depletion alkali post dug blade drama heap khz The case of load-bearing and Qin-Yu film in the journal Seedling slow convex service shears Sichuan snow chain fishing face home of the Yang Zongjio to buy the flag filter silicon carbon stocks sit steam trap gun Li save take Dark Hole criminals you song arc blasting fallacy Tu Jin arm barrier brown land Ah Jian-zun bean pull Mo to thumper around seam police pick dirty ice Cambodian mouth what rice plastic send Zhao shout mat Kang The garden cavity order fragrant Meat Brother house sensitive to forget clothes Sun Ling Ridge cheat Hugh borrow Dan Watanabe planing Tiger pen thin kun lang tea drip shallow hug cave Covered LUN Niang ton of dip sleeve beads Female mom purple play Tower Hammer earthquake old appearance clean cut the front of the suspect PA Flash PO Fierce and sudden disaster, Joe Tang leak smell shen melt chlorine waste stalk male where rob like pulp beside the glass also loyal sing to catch lock especially by Uzhi light allowed to rebel livestock capture rust sweep Bilibao core ye Jian-jiang calcium shoulder teng withered throw rail Hall mix dad 祝励 Ken Wine rope Poor pond dry bubble bag long feeding aluminum soft channel of habitual trade manure wall trend of the anti-dumping air fog Crown Street Hlaninbwe spoke intestinal Fu ji infiltration rui-jing squeeze seconds hang Sam Rotten Sugar Sheng-tao word late silkworm billion moment ";
$len = Mb_strlen ($ch _str, "utf-8");//Kanji 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; Log 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);
Here to take the image of the white background
$bkg = Imagecolorallocate ($im, 255,255,255);
Display the font style, this will put the file in the corresponding directory, if you do not have files, go to the window font file to find a bar.
$FNT = "Simhei.ttf";
Assign some colors to an image
$white =imagecolorallocate ($im, 234,185,95);
To draw an elliptical arc on a picture, specify the next sitting punctuation
Imagearc ($im, 8, A, A, $white);
Imagearc ($im, 7,50, 175, $white);
Draw a line segment on the picture to specify the next sitting punctuation
Imageline ($im, 20,20,180,30, $white);
Imageline ($im, 20,18,170,50, $white);
Imageline ($im, 25,50,80,50, $white);
The number of chaotic points
$noise _num=3000;
$line _num=50;
The colors 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 at 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, the color 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 (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.rar Click here to download this site.

Attention:

The Chinese character verification code executes separately, then obtains the session to discover the verification code and the session content is inconsistent. However, in the IMG tag in the SRC attribute referenced in the Chinese character verification code file, and then get the session, when the two content is consistent.

Interested friends can further refine this.

http://www.bkjia.com/PHPjc/965356.html www.bkjia.com true http://www.bkjia.com/PHPjc/965356.html techarticle PHP Implementation of the formula verification Code and Chinese character Verification code example, PHP code examples in the development of PHP Web site, verification code can effectively protect our form is not maliciously submitted, but if not to make ...

  • 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.