PHP—生成验证码并验证(案例)

项目中经常会遇到一些登陆验证,支付验证等等一系列安全验证的策略。实现方法多种多样,下面就来讲解下如何用php生成简单的文字+数字组合的验证码:

原理解释:
a>实质上是在服务器端随机生成验证码,将其存储在$_SESSION中。
b>然后将验证码写在图片上,将图片发送至客户端,用户输入图片的上的验证码,递交给服务器。
c>服务端再与$_SESSION中存储的信息比对,一致则通过,否则不通过。

第一步:在服务器端如何生成验证码:<yzm.php> 

<?php
    session_start();
    $str='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    //创建画布
    $width = 100;
    $height = 35;
    $img = imagecreatetruecolor($width, $height);
    $color = imagecolorallocate($img,0xcc,0xcc,0xcc);
    //填充颜色
    imagefill($img,0,0,$color);
    //画噪点
    for ($i=0;$i<300;$i++){
        $color = imagecolorallocate($img,rand(0,100),rand(0,100),rand(0,100));
        $x=rand(0,$width);
        $y=rand(0,$height);
        imagesetpixel($img,$x,$y,$color);
    }
    //画噪线
    for ($i=0;$i<8;$i++){
        $color = imagecolorallocate($img,rand(0,100),rand(0,100),rand(0,100));
        $x1=rand(0,$width);
        $y1=rand(0,$height);
        $x2=rand(0,$width);
        $y2=rand(0,$height);
        imageline($img,$x1,$y1,$x2,$y2,$color);
    }
    //画圆
    for ($i=0;$i<6;$i++){
        $color = imagecolorallocate($img,rand(0,255),rand(0,255),rand(0,255));
        imageellipse($img,rand(0,$width),rand(0,$height),30,30,$color);
    }
    //画文字
    $len = strlen($str);
    $font = 'arial.ttf';
    $yzm = "";
    for ($i=0;$i<4;$i++){
        $color = imagecolorallocate($img,rand(0,100),rand(0,100),rand(0,100));
        $index = rand(0,$len-1);
        $chr = substr($str,$index,1);
        $yzm .= $chr;
        $x = 10+$i*20;
        $y = 20;
        //imagettftext(图像资源,字体大小,角度,x坐标,y坐标,$颜色,$字体路径,字符串);
        imagettftext($img,20,rand(-50,50),$x,$y,$color,$font,$chr);
    }
    $_SESSION["yzm"] = $yzm;
    //输出画布
    header('content-type:image/png');
    imagepng($img);
    //销毁画布
    imagedestroy($img);

?>

第二步:将生成的验证码图片返回给客户端<form.php>

<?php
header("Content-type:text/html;charset=utf-8");//避免出现乱码的情况
if(isset($_REQUEST['authcode'])){
    session_start();//使用$_SESSION之前必须使用session_start()
    if(strtolower($_REQUEST['authcode'])==$_SESSION["authcode"]){//$_SESSION['authcode']是服务器端存储的验证码,$_REQUEST['authcode']获取客户端输入的信息
        echo "<font color='#000cc'>输入正确</font>";
    }
    else{
        echo "<font color='#0000cc'>输入错误</font>";
    }
    exit();
}
?>

 

  • 3
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值