适合初学phper-简单图片验证码示例
利用PHP自带生成图片函数,再通过session来存取当前值来获的验证
<?php
session_start();
function random($len)
{
$srcstr="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
mt_srand();
$strs="";
for($i=0;$i<$len;$i++){
$strs.=$srcstr[mt_rand(0,35)];
}
return strtoupper($strs);
}
$str=random(4);
$width = 50;
$height = 25;
@header("Content-Type:image/png");
$_SESSION["code"] = $str;
//echo $str;
$im=imagecreate($width,$height);
$back=imagecolorallocate($im,0xFF,0xFF,0xFF);
$pix=imagecolorallocate($im,187,230,247);
$font=imagecolorallocate($im,41,163,238);
mt_srand();
for($i=0;$i<1000;$i++)
{
imagesetpixel($im,mt_rand(0,$width),mt_rand(0,$height),$pix);
}
imagestring($im, 5, 7, 5,$str, $font);
imagerectangle($im,0,0,$width-1,$height-1,$font);
imagepng($im);
imagedestroy($im);
$_SESSION["psn"] = $str;
?>
把上面代码存为img.php文件,再在引用验证码的页面<img src="img.php" />路径根据实际情况定义。假哪你还加一个刷新功能,可以给img属性加一个ID来,用jquery来刷新当新ID对应的SRC属性,下面贴一下代 码,自己去理解,这里只提供一个思路。
<script type="text/javascript">
function changecode(){
var img = document.getElementById("showing");
img.src = "img.php";
return ;
}
</script>
浙公网安备 33010602011771号