您的位置:首页 > 编程语言 > PHP开发

php验证码

2015-12-30 21:17 661 查看
<?php

/*
* php中验证码的实现
*/

//创建画布
$width=500;
$height=200;

//创建一个真彩色画布
//$img=imagecreatetruecolor($width, $height);

//分配颜色
//$green=imagecolorallocate($img, 0, 255, 0);

//填充画布
//imagefill($img, 0, 0, $green);

//基于图片创建背景图
$bg_file='./bg'.mt_rand(1,3).'.jpg';

$img=imagecreatefromjpeg($bg_file);

//验证码的值
$chars='ABCDEFGHI1234567890';
$chars_len=strlen($chars);
$code_len=4;//码值的长度
$code='';//初始码值的字符串
for($i=0;$i<$code_len;$i++)
{
$rand_index=mt_rand(0, $chars_len-1);
$code.=$chars[$rand_index];
}
//随机分配字符串颜色
$str_color=mt_rand(1, 2)==1?imagecolorallocate($img, 0, 0, 0):imagecolorallocate($img, 255, 255, 255);

//字符串
$font=5;
$x=55;
$y=2;

//居中的方式
$img_w=imagesx($img);
$img_h=imagesy($img);
//字体尺寸
$font_w=imagefontwidth($font);
$font_y=imagefontheight($font);
//字符串宽度
$code_w=$font_w*$code_len;
$code_h=$font_y;

$x=($img_w-$code_w)/2;
$y=($img_h-$code_h)/2;
imagestring($img, $font, $x, $y, $code, $str_color);

//输出
header('Content-Type:image/jpeg');
imagejpeg($img);

//输出到文件  如果写第二个参数则输出到文件,不写则直接输出
//imagepng($img,'./cc.png');
//header('Content-Type:image/png');
//imagepng($img);
?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: