• 6187阅读
  • 0回复

【原创】用PHP生成验证码 [复制链接]

上一主题 下一主题
离线XChinux
 

只看楼主 倒序阅读 楼主  发表于: 2005-07-18
做管理员登录的时候需要一个功能,随机验证码,于是打开PHP手册狂查,因为知道需要用到图像处理函数,于是直接点击“图像处理函数”主题,很快找到要用的资料。
  思路如下:
  用户通过站内链接进入登录界面,显示用户名/密码输入框,外加一个验证码输入框,验证码由后台PHP随机产生,并以图片的形式显示。
 
相关页面源文件(关键部分):

1.validate_code.php
作用:产生随机验证码,并生成图片

<?php
header ("Content-type: image/png");
session_start();
$_SESSION[’validate_code’] = strtoupper(substr(md5(rand()),20,6));
$im = @imagecreate (130, 40)
  or die ("Cannot Initialize new GD image stream");
$background_color = imagecolorallocate ($im, 200, 200, 200);
//设置干扰像素,防止被OCR
for ($i=0;$i<=128;$i++)
{
$point_color = imagecolorallocate ($im, rand(0,255), rand(0,255), rand(0,255));
imagesetpixel($im,rand(2,128),rand(2,38),$point_color);
}
//逐个画上验证码字符
for ($i=0;$i<=5;$i++)
{
$text_color = imagecolorallocate ($im, rand(0,255), rand(0,128), rand(0,255));
$x = 10 + $i * 20;
$y = rand(5,20);
imagechar ($im, 5, $x, $y, $_SESSION[’validate_code’]{$i}, $text_color);
}
//输出PNG图像
imagepng ($im);
imagedestroy ($im);
?>


下面是如何使用:
validate_code.html

<html>
<head>
</head>
<body>
<form>
用户名:<input type="text" name="username" value=""><br>
密 码:<input type="password" name="password" value=""><br>
验证码:<input type="text" name="validate_code" value=""><img src="validate_code.php">
<input type="button" name="buttonsubmit" value="提交">
</body>
</html>
[ 此贴被XChinux在2005-09-13 13:58重新编辑 ]
二笔 openSUSE Vim N9 BB10 XChinux@163.com 网易博客 腾讯微博
承接C++/Qt、Qt UI界面、PHP及预算报销系统开发业务
快速回复
限100 字节
 
上一个 下一个