Home>Article>Backend Development> PHP implements Chinese character verification code
This article mainly introduces the implementation of Chinese character verification code in PHP. Interested friends can refer to it. I hope it will be helpful to everyone.
Now more and more websites are beginning to use Chinese character verification codes, which not only increases the intimacy of our people, but also increases the difficulty of machine cracking. Here I will briefly explain it. . .
Create background canvas
$image = imagecreatetruecolor(200, 60); $background = imagecolorallocate($image, 255, 255, 255); imagefill($image, 0, 0, $background);
Draw interference points
for ($i=0; $i < 300; $i++) { $pixColor = imagecolorallocate($image, rand(150, 240), rand(150, 240), rand(150, 240)); $pixX = rand(10, 190); $pixY = rand(5, 55); imagesetpixel($image, $pixX, $pixY, $pixColor); }
Draw interference lines
//4条水平线 for ($i=0; $i < 5; $i++) { $lineColor = imagecolorallocate($image, rand(50, 150), rand(50, 150), rand(50, 150)); $lineX1 = 0; $lineX2 = 300; $lineY1 = ($i + 1) * 12; $lineY2 = ($i + 1) * 12; imageline($image, $lineX1, $lineY1, $lineX2, $lineY2, $lineColor); } //10条垂直线 for ($i=0; $i < 30; $i++) { $lineColor = imagecolorallocate($image, rand(50, 150), rand(50, 150), rand(50, 150)); $lineX1 = ($i + 1) * 10; $lineX2 = ($i + 1) * 10; $lineY1 = 0; $lineY2 = 60; imageline($image, $lineX1, $lineY1, $lineX2, $lineY2, $lineColor); }
Drawing Chinese characters
$text = array('栀', '子', '花', '开'); for ($i=0; $i < 4; $i++) { $textColor = imagecolorallocate($image, rand(20, 100), rand(20, 100), rand(20, 100)); $textX = $i * 50 + 10; $textY = rand(40, 60); imagettftext($image, 30, rand(20, 50), $textX, $textY, $textColor, "/Library/Fonts/华文仿宋.ttf", $text[$i]); }
Note here, the font file must support Chinese
Encoding must use utf-8, do you remember to convert gbk Chinese? [iconv function can help you]
Output image
header("Content-Type:image/png"); imagepng($image);
Destroy resources
imagedestroy($image);
After a rough process, let’s do it , the Chinese verification code will be displayed. Of course, when a website is used, there will be a Chinese character library seed, from which a specific number of Chinese characters are randomly selected and displayed, and finally recorded in the session for verification.
Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.
Related recommendations:
Basic knowledge and application of php design patterns
php image file operation encapsulation class
Those knowledge points that are often confused in PHP
The above is the detailed content of PHP implements Chinese character verification code. For more information, please follow other related articles on the PHP Chinese website!