使用session验证输入的验证码是否正确

为了让我记忆有效,直接贴代码了。

1.identify.php

<?php

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

    header("content-type:image/png; charset=utf-8");
    session_start();
    srand((double)microtime() * 1000000);
    $imagewidth = 60;
    $imageheight = 20;
    $authimage = imagecreate($imagewidth, $imageheight); // 新建一个基于调色板的图像
    $black = imagecolorallocate($authimage, 0, 0, 0); // 为一副图像分配颜色
    $white = imagecolorallocate($authimage, 255, 255, 255);
    $red = imagecolorallocate($authimage, 255, 0, 0);
    $gray = imagecolorallocate($authimage, 200, 200, 200);
    $fontfile='C:/windows/fonts/simhei.ttf';
    //背景色为灰色
    imagefill($authimage, 0, 0, $gray);

    //随机生成一些干扰像素
    for($i=0;$i<400;$i++){
        $randcolor = imagecolorallocate($authimage, rand(10, 255), rand(10, 255), rand(10, 255));
        imagesetpixel($authimage,rand()%$imagewidth, rand()%$imageheight, $randcolor);  // 画一个单一像素
    }

    //随机划线
    for($i = 0; $i < 6; $i++)
     {
         imageline($authimage, rand()%$imagewidth, rand()%$imageheight, 
         rand()%$imagewidth, rand()%$imageheight, $black);  // 画一条线段
     }
     $array = "0123456789abcdefghijklmnopqrstuvwxyz";
     $authcode='';
    for($i = 0; $i < 4; $i++)
     {
      $authcode .=substr($array, rand(0, 35), 1);  // 返回字符串的子串从array中rand位置开始,长度为1
     }
     imagettftext($authimage, 20, 0, 0, $imageheight, $red, $fontfile, $authcode); // 用true type字体向图像写入文本
     $_SESSION['auth'] = $authcode;
     imagepng($authimage); // 以png格式输出文件
     imagedestroy($authimage); // 销毁图像

思路:1.新建图像imagecreate    2.配置颜色imagecolorallocate    3.添加文本imagettftext, 添加像素imagesetpixel, 添加线imageline
2.index.php

<html>
    <meta charset="utf-8"/>
    <title>验证码</title>
    <body>
        <form action="id.php" method="post">
            <tr>
                <input type="text" name="identify"/>
                <image src="identify.php"/>
                <input type="submit" name="yz" value="验证"/>
            </tr>
        </form>
    </body>
</html>
    
    
3.id.php

<?php

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
header("content-type:text/html; charset=utf-8");
session_start();
echo $_POST['identify'];
echo "<br>";
echo $_SESSION['auth'];
if(!strcmp($_POST['identify'], $_SESSION['auth'])){
    echo '验证通过';
}else{
    echo '验证未通过';
}
session_close();
总结在用session的时候,记着打开session,identify.php产生的是一张图片所以可以直接使用<image src="idetify.php"/>来显示

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值