PHP生成图片验证码
新建画布
imagecreatetruecolor(宽,高);
新建颜色
imagecolorallocate(图像名称,R,G,B);
绘制点
imagesetpixel(图像,点x,点y,颜色);
绘制线
inageline(图像,起点x,起点y,终点x,终点y,颜色);
随机字符
大写字符ASCII:65-90
小写字母ASCII:97-122
将数字转换为对应ASCII字符:sprintf('%c',数值)
将字符转换为图像显示
imagettftext(图像名称,文字大小,角度,位置x,位置y,颜色,文字库)
显示图像
imagejpeg(图像名称)
清除图像
imagedestror()
显示验证码使用图像控件
<img src="验证码文件"/>
代码
<?php
//新建画布
$image = imagecreatetruecolor(200,100);
//新建颜色
$white = imagecolorallocate($image,255,255,255);
$black = imagecolorallocate($image,0,0,0);
//绘制点
for($i=1;$i<=100;$i++){
imagesetpixel($image,rand(0,200),rand(0,100),$white);
}
//绘制线
for($i=1;$i<=10;$i++){
imageline($image,rand(0,200),rand(0,100),rand(0,200),rand(0,100),$white);
}
//随机字符
$str='';
for($i=1;$i<=6;$i++){
switch(rand(1,3))
{
//大写字母
case '1':
$ch=sprintf('%c',rand(65,90));
break;
//小写字母
case '2':
$ch=sprintf('%c',rand(97,122));
break;
//随机数字
case '3':
$ch=rand(0,9);
break;
}
$str=$str.$ch;
}
//转换为图形
imagettftext($image,35,0,2,70,$white,'./font/Elephant.ttf',$str);
//显示图像
imagejpeg($image);
//清除图像
imagedestroy();
?>
效果图如下
验证码判断
1.启用session
session_start();
2.创建session
$SESSION['名称'] = 值;
3.使用
$_SESSION['名称'];
4.删除
unset($_SESSION[‘名称’]);
5.清除所有
$_SESSION =array();
session_destroy();
原文:大专栏 PHP基础笔记2(验证码)