学习使用php实现汉字验证码
<?php
//开启session ,方便验证
session_start();
//创建背景画布
$image = imagecreatetruecolor(200, 60);
$background = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $background);//创建背景画布
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);
}//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);
}//汉字库
$text_str = '君|不|见|黄|河|之|水|天|上|来|奔|流|到|海|不|复|回|君|不|见|高|堂|明|镜|悲|白|发|朝|如|青|丝|暮|成|雪|人|生|得|意|须|尽|欢|莫|使|金|樽|空|对|月|天|生|我|材|必|有|用|千|金|散|尽|还|复|来|烹|羊|宰|牛|且|为|乐|会|须|一|饮|三|百|杯|岑|夫|子|丹|丘|生|将|进|酒|杯|莫|停|与|君|歌|一|曲|请|君|为|我|倾|耳|听|钟|鼓|馔|玉|不|足|贵|但|愿|长|醉|不|愿|醒|古|来|圣|贤|皆|寂|寞|惟|有|饮|者|留|其|名|陈|王|昔|时|宴|平|乐|斗|酒|十|千|恣|欢|谑|主|人|何|为|言|少|钱|径|须|沽|取|对|君|酌|五|花|马|千|金|裘|呼|儿|将|出|换|美|酒|与|尔|同|销|万|古|愁';$text = explode('|', $text_str);$text_count = bcsub(count($text), 1);//创建背景画布
$text_new = '';
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);//随机生成数字$rand_i = rand(0, $text_count);$text_new .= $text[$rand_i];imagettftext($image, 30, rand(20, 50), $textX, $textY, $textColor, "simhei.ttf", $text[$rand_i]);
}
//存入session
$_SESSION['text_new'] = $text_new;header("Content-Type:image/png");
imagepng($image);?>
效果图