dd

PHP检测中文验证码实例演示

汉王 PHP+MySQL 收藏

PHP生成验证码,注意font字体路径要对,否则显示图片不存在

session_start(); 
 
//1>设置验证码图片大小的函数 
$image = imagecreatetruecolor(200, 60); 
//5>设置验证码颜色 imagecolorallocate(int im, int red, int green, int blue); 
$bgcolor = imagecolorallocate($image, 255, 255, 255); //#ffffff 
//6>区域填充 int imagefill(int im, int x, int y, int col)  (x,y) 所在的区域着色,col 表示欲涂上的颜色 
imagefill($image, 0, 0, $bgcolor); 
//7>设置ttf字体 
$fontface = 'simhei.ttf'; 
//7>设置字库,实现简单的数字储备 
$str = '天地不仁以万物为刍'; 
//str_split()切割字符串为一个数组,一个中文在utf_8为3个字符 
$strdb = str_split($str, 3); 
//>11 
$captcha_code = ''; 
//8>生成随机的汉子 
for ($i = 0; $i < 4; $i++) { 
    //设置字体颜色,随机颜色 
    $fontcolor = imagecolorallocate($image, rand(0, 120), rand(0, 120), rand(0, 120));            //0-120深颜色 
    //随机选取中文 
    $in = rand(0, count($strdb)); 
    $cn = $strdb[$in]; 
    //将中文记录到将保存到session的字符串中 
    $captcha_code .= $cn; 
    /* imagettftext (resource $image ,float $size ,float $angle ,int $x ,int $y,int $color, 
      string $fontfile ,string $text ) 幕布 ,尺寸,角度,坐标,颜色,字体路径,文本字符串 
      mt_rand()生成更好的随机数,比rand()快四倍 */ 
    imagettftext($image, mt_rand(20, 24), mt_rand(-60, 60), (40 * $i + 20), mt_rand(30, 35), $fontcolor, $fontface, $cn); 
} 
//11>存到session 
$_SESSION['erdangjiade_code'] = $captcha_code;
Ajax检测验证码
function checkCode() { 
    $.post("ajax.php", {code: $("#input_code").val()}, function(data) { 
        if (data == '1') { 
            alert("验证码正确!"); 
        } else { 
            alert("验证码错误!"); 
        } 
 
    }, "json") 
}
ajax.php判断传过来的验证码code和系统自动生成在session中的erdangjiade_code是否一致。若返回1则说明验证码正确,否则验证不通过。
SESSION_START(); 
$code = $_POST['code']; 
$code_session = isset($_SESSION["erdangjiade_code"])?$_SESSION["erdangjiade_code"]:""; 
if (strtolower($code) == $code_session) { 
    echo "1"; 
} else { 
    echo "-1"; 
}
点击验证码图片,切换新的验证码
function changeCode(obj) { 
    obj.attr("src", 'code.php?' + Math.random()); 
}

下载地址

dd