php新手,写了一个web登录界面,除了用户名,密码,感觉有个验证码会比较cool一点,便根据参考书的简单介绍,写了一个image.php来生成简单的图片验证码,颇有感慨,分享一下。
1、图片验证码生成步骤
产生随机字符串(假设只需6位),使用session进行保存,以便验证
<?php
$string = "abcdefghijklmnopqrstuvwxyz0123456789";
$str = "";
for($i=0;$i<6;$i++){
$pos = rand(0,35);
$str .= $string{$pos};
}
session_start();
$_SESSION['img_number'] = $str;
创建一张简单的图片(80X20),设置背景色,文本色,再加一些干扰线,干扰素
$img_handle = Imagecreate(80, 20);
$back_color = ImageColorAllocate($img_handle, 255, 255, 255);
$txt_color = ImageColorAllocate($img_handle, 0,0, 0);
for($i=0;$i<3;$i++)
{
$line = ImageColorAllocate($img_handle,rand(0,255),rand(0,255),rand(0,255));
Imageline($img_handle, rand(0,15), rand(0,15), rand(100,150),rand(10,50), $line);
}
for($i=0;$i<200;$i++)
{
$randcolor = ImageColorallocate($img_handle,rand(0,255),rand(0,255),rand(0,255));
Imagesetpixel($img_handle, rand()%100 , rand()%50 , $randcolor);
}
填充图片背景色,再将产生的随机字符串填充图片
Imagefill($img_handle, 0, 0, $back_color);
ImageString($img_handle, 28, 10, 0, $str, $txt_color);
清空输出缓存区,再生成验证码图片,并显示图片
ob_clean();
header("Content-type: image/png");
Imagepng($img_handle);
2、图片验证码的引用
在form表单中添加验证码图片,src=“image.php” 就是根据上面步骤用于产生验证码图片的php,为了增加效果,添加了js刷新验证码的功能,可以参考。
<form id="form1" name="form1" method="post" action="post.php">
<input type="text" name="code" />
<img src="image.php" id = "refresh" title="刷新验证码" align="absmiddle" onclick="document.getElementById('refresh').src='image.php' ">
<font color="#ffffff">点击图片刷新</font>
<input type="submit" value="登录"/>
</form>
3、 验证码的验证
在post.php中使用第一步保存字符串的session与用户输入的验证码进行匹配。
session_start();
if($_POST['code'] == $_SESSION['img_number']){
echo "验证码正确";
}else{
echo "验证码错误";
}
4、 效果展示
生成的验证码图片

正文完
微信搜一搜“奇悦电脑科技”或扫描二维码关注我们


