发一个动态生成验证码的FUNCTION~

stan23 2004-01-01 01:32:19
昨天写程序时用到的,在版块里找了几个,都是一个模子,而且也不太好用,所以我就自己写了一个,扩展功能强些,拿出来和大家分享:

================================================================
<?php

/*
creat_code.php
*/

/*

creat_code()
coded by stan@china.com
http://www.okphp.com
动态生成验证码,可选择写入SESSION

$width :图片宽
$height : 图片高
$space : 字符间距(中心间距)
$size : 字符大小(1-5)
$line_num : 干扰线条数
$length : 字符串长度
$sname :SESSION名称(供下一步验证之用)

*/

/*
例子:
*/
session_start();
creat_code(45,15,10,3,5,5,"code_str");
/*
*/


function creat_code($width, $height, $space, $size, $line_num, $length, $sname="") {


$left = 3; // 字符左间距
$top = 1; // 右间距
$move = 3; //上下错位幅度

// 生成字符串
srand((double)microtime()*1000000);
$possible = "0123456789"."ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$authstr = "";
while(strlen($authstr) < $length) {
$authstr .= substr($possible, rand(0,strlen($possible)), 1);
}

// 设置SESSION
if ($sname != "") {
$_SESSION[$sname] = $authstr;
}
// 初始化图片
$image = imagecreate($width,$height);

// 设定颜色
$black = ImageColorAllocate($image, 0, 0, 0);
$white = ImageColorAllocate($image, 255, 255, 255);
$gray = ImageColorAllocate($image, 80, 80, 80);
$silver = ImageColorAllocate($image, 240, 240, 240);
$msilver = ImageColorAllocate($image, 220, 220, 220);
$bg_white = ImageColorAllocate($image, 255, 255, 255);

// 生成背景
imagefill($image,0,0,$gray);


// 画出字符
for ($i = 0; $i < strlen($authstr); $i++) {
$y = ($i%2)*$move + $top;
imagestring($image, $size, $space*$i+$left, $y, substr($authstr,$i,1), $white);
}

// 画出横向干扰线
if ($i > 0) {
$line_space = ceil($height/($line_num+2));
for ($i = 1; $i <= $line_num; $i++) {
$y = $line_space*$i;
imageline($image, 0, $y, $width, $y, $silver);
}
}

// 输出图象
Header("Content-type: image/PNG");
ImagePNG($image);
ImageDestroy($image);
}
?>

================================================================

<?
/*
login.php
*/

session_start();
?>
<FORM METHOD=POST ACTION="confirm.php">
<input type=text name=code>
<img src="creat_code.php">
<INPUT TYPE="submit" name="sub">
</FORM>
?>

================================================================

<?
/*
confirm.php
*/

session_start();
if($_REQUEST["code"]!=$_SESSION["code_str"]){
die("wrong!");
}else{
echo "ok";
};
?>
...全文
89 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
dgmichaelz 2004-04-13
  • 打赏
  • 举报
回复
up
xucarry 2004-01-02
  • 打赏
  • 举报
回复
支持
jxyuhua 2004-01-02
  • 打赏
  • 举报
回复
mark
野马 2004-01-01
  • 打赏
  • 举报
回复
收藏

21,891

社区成员

发帖
与我相关
我的任务
社区描述
从PHP安装配置,PHP入门,PHP基础到PHP应用
社区管理员
  • 基础编程社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧