php简单验证码:
1:创建验证码图像:可封装成函数再调用:
2:将随机码保存在session中,调用要开启session;
3:js点击刷新验证码
function code($_width = 75,$_height = 25,$_rnd_code = 4,$_flag = true){
//随机码个数
// $_rnd_code = 4;
//创建随机码
for($i=0;$i<$_rnd_code;$i++){
$_nmsg.= dechex(mt_rand(0,15)); //16进制,注意累加到4位
}
// 保存在session
$_SESSION['code'] = $_nmsg; //保存在session里超级全局变量可以跨页面
//创建图像
$_img = imagecreatetruecolor($_width, $_height);
//白色背景
$_write = imagecolorallocate($_img, 255, 255, 255);
//填充
imagefill($_img, 0, 0, $_write);
// 输出验证码
for($i = 0;$i<strlen($_SESSION['code']);$i++){
//颜色调深 随机颜色
$_rnd_color = imagecolorallocate($_img,mt_rand(0,150),mt_rand(0,150),mt_rand(0,150));
// 输出并调整位置
imagestring($_img,5,$i*$_width/$_rnd_code+mt_rand(1,10),mt_rand(1,$_height/2),$_SESSION['code'][$i],$_rnd_color);
}
//输出图像
header('Content-Type:image/png');
imagepng($_img);
// 销毁
imagedestroy($_img);
}
//code.php调用:
session_start();//开启session
code(75,25,4,false);
//js刷新验证码
<img src="code.php" onclick="javascript:this.src='code.php?tm='+Math.random()">