新建一个 yzm.php  用于返回验证码图片  注意里面的字体文件路径  自己找一个字体文件放进去即可


此代码 我把干扰线去掉了,喜欢留着的 可以去掉注释

但根据我的验证码识别经验来看  那种干扰线对机器识别来说 如同虚设~只会难为用户  根本不会给机器增加难度



<?php
session_start();
$_SESSION['yzm']="";
$font = 'font/consola.ttf';  //字体文件路径


	 function rand_str($length) {
        // 验证码中所需要的字符
        $chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
        $str = '';
        for($i = 0; $i < $length; $i++)
        {
            // 随机截取 $chars 中的任意一位字符;
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
    function rand_color($image){
        // 生成随机颜色
        return imagecolorallocate($image, rand(127, 255), rand(127, 255), rand(127, 255));
    }
    $image = imagecreate(200, 100);
    imagecolorallocate($image, 0, 0, 0);
    for ($i=0; $i <= 9; $i++) {
        // 绘制随机的干扰线条
        //imageline($image, rand(0, 200), rand(0, 100), rand(0, 200), rand(0, 100), rand_color($image));
    }
    for ($i=0; $i <= 100; $i++) {
        // 绘制随机的干扰点
        //imagesetpixel($image, rand(0, 200), rand(0, 100), rand_color($image));
    }
    $length = 4;//验证码长度
    $str = rand_str($length);//获取验证码
		$_SESSION['yzm']=$str;

    for ($i=0; $i < $length; $i++) {
        // 逐个绘制验证码中的字符
        imagettftext($image, rand(20, 38), rand(-60, 60), $i*50+25, rand(30,70), rand_color($image), $font, $str[$i]);
    }
    header('Content-type:image/jpeg');
    imagejpeg($image);
    imagedestroy($image);
?>

再需要显示验证码的地方 加上以下代码即可

<img onclick="this.src='yzm.php?'+Math.random()" style="width:100px;height:50px;cursor:pointer;" src="yzm.php?<?=time();?>">

再接收提交信息的页面  可以使用 if($_POST['yzm']!=$_SESSION['yzm']) 来判断验证码是否正确