您的位置:首页 > 编程语言 > PHP开发

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

2016-11-10 20:01 411 查看
为了让我记忆有效,直接贴代码了。

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"/>来显示
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  验证码 session php
相关文章推荐