网上有不少用php写验证码的代码,不过效果都不太喜欢,了解了一下原理就自己写了一个,字体采用的是Consolas.ttf
<?php
if(!isset($_SESSION)) session_start();
$png_width=88;
$png_height=31;
$captcha_length=4;
$captcha_content=captcha_content($captcha_length);
$_SESSION['captcha']=$captcha_content;
$img=imagecreate($png_width,$png_height);
$png_bgcolor=imagecolorallocate($img,165,178,170);
imagerectangle($img,0,0,$width,$height,$png_bgcolor);
for($i=0;$i<$captcha_length;$i++){
$char_color=imagecolorallocate($img,mt_rand(50,200),mt_rand(50,150),mt_rand(50,200));
$char_angle=mt_rand(-30,30);
$char_x=$i*17+mt_rand(-1,8);
$char_y=mt_rand(25,31);
imagettftext($img,25,$char_angle,$char_x,$char_y,$char_color,'Consola.ttf',$captcha_content[$i]);
}
for($i=0;$i<100;$i++){
$pixel_color=imagecolorallocate($img,mt_rand(50,200),mt_rand(50,150),mt_rand(50,200));
imagesetpixel($img,mt_rand(1,$png_width-1),mt_rand(1,$png_height-1),$pixel_color);
}
for($i=0;$i<30;$i++){
$line_color=imagecolorallocate($img,mt_rand(0,250),mt_rand(0,250),mt_rand(0,250));
$line_x=mt_rand(1,$png_width-1);
$line_y=mt_rand(1,$png_height-1);
imageline($img,$line_x,$line_y,$line_x+mt_rand(0,4)-2,$line_y+mt_rand(0,4)-2,$line_color);
}
function captcha_content($captcha_length){
$char_source="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghiklmnopqrstuvwxyz";
for($i=0;$i<$captcha_length;$i++){
$num=mt_rand(0,61);
$captcha_content.=$char_source[$num];
}
return $captcha_content;
}
ob_clean();
header('Content-type:image/png');
imagepng($img);
imagedestroy($img);
?>