Home  >  Article  >  Backend Development  >  The idea of ​​​​implementing a simple Chinese character verification code in PHP

The idea of ​​​​implementing a simple Chinese character verification code in PHP

藏色散人
藏色散人forward
2019-09-25 09:17:062308browse

Nowadays, more and more websites have begun 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(&#39;栀&#39;, &#39;子&#39;, &#39;花&#39;, &#39;开&#39;);
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.

The above is the detailed content of The idea of ​​​​implementing a simple Chinese character verification code in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete