<?php 
    //文件头... 
    header("Content-type: image/png"); 
    //创建真彩色白纸 
    $im = @imagecreatetruecolor(50, 20) or die("建立图像失败"); 
    //获取背景颜色 
    $background_color = imagecolorallocate($im, 255, 255, 255); 
    //填充背景颜色(这个东西类似油桶) 
    imagefill($im,0,0,$background_color); 
    //获取边框颜色 
    $border_color = imagecolorallocate($im,200,200,200); 
    //画矩形,边框颜色200,200,200 
    imagerectangle($im,0,0,49,19,$border_color);
    //逐行炫耀背景,全屏用1或0 
    for($i=2;$i<18;$i++){ 
        //获取随机淡色         
        $line_color = imagecolorallocate($im,rand(200,255),rand(200,255),rand(200,255)); 
        //画线 
        imageline($im,2,$i,47,$i,$line_color); 
    }
    //设置字体大小 
    $font_size=12;
    //设置印上去的文字 
    $Str[0] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 
    $Str[1] = "abcdefghijklmnopqrstuvwxyz"; 
    $Str[2] = "01234567891234567890123456";
    //获取第1个随机文字 
    $imstr[0]["s"] = $Str[rand(0,2)][rand(0,25)]; 
    $imstr[0]["x"] = rand(2,5); 
    $imstr[0]["y"] = rand(1,4);
    //获取第2个随机文字 
    $imstr[1]["s"] = $Str[rand(0,2)][rand(0,25)]; 
    $imstr[1]["x"] = $imstr[0]["x"]+$font_size-1+rand(0,1); 
    $imstr[1]["y"] = rand(1,3);
    //获取第3个随机文字 
    $imstr[2]["s"] = $Str[rand(0,2)][rand(0,25)]; 
    $imstr[2]["x"] = $imstr[1]["x"]+$font_size-1+rand(0,1); 
    $imstr[2]["y"] = rand(1,4);
    //获取第4个随机文字 
    $imstr[3]["s"] = $Str[rand(0,2)][rand(0,25)]; 
    $imstr[3]["x"] = $imstr[2]["x"]+$font_size-1+rand(0,1); 
    $imstr[3]["y"] = rand(1,3);
    //写入随机字串 
    for($i=0;$i<4;$i++){ 
        //获取随机较深颜色 
        $text_color = imagecolorallocate($im,rand(50,180),rand(50,180),rand(50,180)); 
        //画文字 
        imagechar($im,$font_size,$imstr[$i]["x"],$imstr[$i]["y"],$imstr[$i]["s"],$text_color); 
    }
    //显示图片 
    imagepng($im); 
    //销毁图片 
    imagedestroy($im); 
?>
例2,漂亮的PHP图片验证码实例
完整代码:
 
例3,php5 图片验证码实例代码
php5生成图片验证码的例子。
需要用到php GD库函数: 
1,imagecreatetruecolor -----创建一个真彩色的图像 
imagecreatetruecolor(int x_size,int y_size) //x表示宽,y表示高 
2,imagecolorallocate 为一幅图像分配颜色(调色板) 
imagecolorallocate(resource image,int red,int green,int blue)//red,green,blue----三原色 
3,imagestring 绘图函数 
iamgestring(resource image,font,int x,int y,内容,颜色); 
4,输出函数 
php的header是定义头的动作,php5中支持3中类型: 
1,Content-type:xxxx/yyyy 
2,Location:xxxx:yyyy/zzzz 
3,Status:nnn xxxxxx 
xxxx/yyyy表示内容文件的类型 
如:image/gif 
image/jpeg 
image/png 
例子:header("Content-type:image/jpeg") 
GD库中有对应的image类型 
imagejpeg(),imagegif(),imagepang() 
5,imageline画线函数 
iamgeline(resource image,int x1,int y1,int x2,int y2,int color); 
image ---图片 
x1 ---启始坐标 
y1 
x2 ---终点坐标 
y2 
6,imagesetpixel画点函数 
imagesetpixel(resource image,int x,int y,int color) 
7,imagettftext带字体的写入函数 
imagettftext(resource image,float size,float angle,int x,int y,int color,string fontfile,string text) 
8,php验证码插入中文的方法 
iconv("gb2312","utf-8","字符串"); //首先要将文字转换成utf-8格式 
9,随机函数 
1,rand([int min,int max]) //rand(1,4) 生成1-4的数 
2, dechex(十进制数) //转换为十六进制
生成验证码的步骤: 
生成随机数 -- 创建图片 -- 随机数写成图片 --保存在session中
输入验证码例子 
gdchek.php 
 
login.php