我们为什么需要验证码?
- 需要判断正在执行操作的另一方,是真正的人/或者是非人(机器人/脚本/程序)。
生产验证码的基本步骤?
- 产生效验数据
- 产生干扰数据
- 生成图片
- 让用户看到图片
- 验证真实性
PHP做验证码主要用GD库来实现。
GD
- resource imagecreatetruecolor(int $width,int $height);
- 创建一个图片 返回一个图像标示符
- imagecolorallocate (resource $image, 255, 255, 255);
- 分配颜色 输入资源标示符+RGB颜色 返回一个标示符
- // 如果想要显示透明度 可以用 imagecolorallocatealpha() 函数;
- bool imagefill ( resource $image, int $x, int $y, int $color);
- 区域填充 在image资源上,开始坐标为x,y 填充 color
- bool imagesetpixel ( resource $image, int x,int y, int $color);
- 在image资源上 在x,y坐标产生一个像素的color颜色的点
- bool imageline ( resourcce $image, int $x1, int $y1, int $x2, int $y2, int $color);
- 在image资源上,从 x1,y1画到 x2,y2,产生一条颜色color的线段
- bool imagestring ( resource $image, int $fontsize, int $x,int $y, string $string, int $color );
- 在image资源上 ,从 x,y开始花上字符串string,并且颜色是color,字体大小是fontsize
其他需要掌握的函数
- string substr( string $string , int $start [, int $length ] );
- 返回 字符串。 从源字符串string上,从start开始 到长度为length处截取 。
- int rand ( int $min, int $max );
- 返回min到max直接的随机数。
如果你还要验证的话
- $_SESSION[]
- session 全局变量需要知道
- bool session_start(void);
- 创建新会话或者重用现有会话。
- $_REQUEST[]
- request 全局变量需要了解
等等 你需要了解更多,请查看 php手册 ,边学习边看手册是一个不错的方法。
最后, 是练习的代码:
[php]
<?php
session_start();
// create image
$image = imagecreatetruecolor(100, 30);
// color image
$bgcolor = imagecolorallocate($image, 255, 255, 255);
// put color
imagefill($image, 0, 0, $bgcolor);
// create pixel
for ($i=0; $i < 200; $i++) {
$x=rand(0,200);
$y=rand(0,30);
$pixcol = imagecolorallocate($image, rand(1,200), rand(1,200), rand(1,200));
imagesetpixel($image, $x, $y, $pixcol);
}
// create line
for ($i=0; $i < 4; $i++) {
$linecolor = imagecolorallocate($image, rand(100,200), rand(100,200), rand(100,200));
imageline($image, rand(0,50), rand(0,30), rand(0,100), rand(0,30), $linecolor);
}
// create unique rand int
for ($i=0; $i < 4; $i++) {
$num = rand(0,9);
$numcolor = imagecolorallocate($image, rand(0,150), rand(0,150), rand(0,150));
$x = ($i+1)*20;
$y = rand(0,15);
imagestring($image, 6, $x, $y, $num, $numcolor);
}
// create unique sting
$yzmyz = ”;
for ($i=0; $i < 4; $i++) {
$strcol = imagecolorallocate($image, rand(0,150), rand(0,150), rand(0,150));
$data=’abcdefghijkmnpqrstuvwxy123456789′;
$str = substr($data, rand(0,strlen($data)-1),1);
$yzmyz .= $str;
imagestring($image, 6, ($i+1)*20, rand(0,15), $str, $strcol);
}
$_SESSION[‘yzmyz’] = $yzmyz;
header(‘Content-type: image/png’);
imagepng($image);
// drop image
imagedestroy($image);
?>
[/php]