php 验证码详细生成与使用方法
注意:以下代码需要打开php教程的gd库,修改php.in文件的配置,把已经注释掉的行之前的分号取消即可:extension=php_gd2.dll。
$width = 165;
$height = 120;
$image = imagecreatetruecolor($width,$height);
$bg_color = imagecolorallocate($image,255,255,255);
$tm = imagecolorallocate($image,255,0,0);
imagefilledrectangle($image,0,0,$width,$height,$bg_color);
imagefill($image,0,0,$bg_color);
/*
//$text = random_text(5);
$text = "ffff";
$font = 8;
$struft=iconv("gbk","utf-8",$text);
$x = imagesx($image);
$y = imagesy($image);
$fg_color = imagecolorallocate($image,233,14,91);
imagestring($image,$font,$x,$y,$struft,$fg_color);
$_session['captcha'] = $text;
*/
header("content-type:image/png");
imagepng($image);
imagedestroy($image);
实例二
validate.php
采用了session识别,稍微改进了一下目前网络上流传的php验证码,加入杂点,数字颜色随机显示,控制4位数字显示;
<?
session_start();
//生成验证码图片
header("content-type: image/png");
$im = imagecreate(44,18);
$back = imagecolorallocate($im, 245,245,245);
imagefill($im,0,0,$back); //背景srand((double)microtime()*1000000);
//生成4位数字
for($i=0;$i<4;$i++){
$font = imagecolorallocate($im, rand(100,255),rand(0,100),rand(100,255));
$authnum=rand(1,9);
$vcodes.=$authnum;
imagestring($im, 5, 2+$i*10, 1, $authnum, $font);
}for($i=0;$i<100;$i++) //加入干扰象素
{
$randcolor = imagecolorallocate($im,rand(0,255),rand(0,255),rand(0,255));
imagesetpixel($im, rand()%70 , rand()%30 , $randcolor);
}
imagepng($im);
imagedestroy($im);$_session['vcode'] = $vcodes;
?>
下面看完整实例
<?php
@header("content-type:text/html; charset=utf-8");
//打开session
session_start();
?>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>php验证码示例</title>
</head>
<body>
验证码:<br/>
<iframe id="iimg" height="100" width=300 src="img.php" frameborder="0" ></iframe>
<br/>
<input type=button value="看不清,换一张" onclick="iimg.location.reload();">
<br>
<form action="validate.php" method="post">
输入验证码:<input name="imgid" style="width:60">
<input type="submit" value="确定">
</form>
</body>
</html>
php判断用户输入的验证码是否与系统生成的一致
<?php @header("content-type:text/html; charset=utf-8");
//开启session
session_start();
//得到用户输入的验证码,并转换成大写
$imgid_req = $_request['imgid'];
$imgid_req = strtoupper($imgid_req);
//验证该字符串是否注册了session变量
if (session_is_registered($imgid_req)) {
echo "<font color=blue >通过验证!</font>";
} else {
echo "<font color=red >验证错误!</font>";
}
//关闭session,以清除所有注册过的变量
session_destroy();
?>
补充:Php教程,Php安全