当前位置: 代码迷 >> PHP >> 验证码有关问题求解决
  详细解决方案

验证码有关问题求解决

热度:122   发布时间:2016-04-28 18:31:49.0
验证码问题求解决
问题:怎样能将图片中的验证码储存起来用于后期的验证?

verficode.php 页面
<?php
ob_clean();
for($i=0;$i<4;$i++){
$num.=dechex(rand(0,15));
}
$num=substr($num,-4,4);
$nowimage=imagecreate(100,30);
imagecolorallocate($nowimage,240,240,240);
for($i=0;$i<strlen($num);$i++){
$font=mt_rand(3,5);
$x=mt_rand(1,8)+100*$i/4;
$y=mt_rand(1,50/4);
$color=imagecolorallocate($nowimage,rand(0,150),rand(0,150),rand(0,150));
imagestring($nowimage,$font,$x,$y,$num[$i],$color);
}
for($i=0;$i<200;$i++){
$randcolor=imagecolorallocate($nowimage,rand(200,255),rand(200,255),rand(200,255));
imagesetpixel($nowimage,rand()%70,rand()%20,$randcolor);
}
header("content-type:image/png");
imagepng($nowimage);
imagedestroy($nowimage);
?>

index.php 页面
<html>
<head>
<title>明日商城</title>
<link rel="stylesheet" href="css/index.css" text="text/css" />
<script text="text/javascript" src="js/login.js"></script>
</head>
<body>
<div id="header">
<?php 
require 'conn/head.php';
?>
</div>
<div id="content">
<div id="left">
<div id="top">
<div class="title">用户登录</div>
<div class="content">
<label>用户名:</label><input type="text" name="user" class="input-text" />
<label>密码:</label><input type="password" name="pwd" class="input-text" />
<label>验证码:</label><input type="text" name="verficode" id="verficode" class="input-text" /><img src='verficode.php' style="cursor:pointer;" id="changecode" align="absMiddle" onclick="return change();" />
<a href="">换一张</a>
</div>
</div>
<div id="middle">
<div class="title"></div>
<div class="content"></div>
</div>
<div id="bottom">
<div class="title"></div>
<div class="content"></div>
</div>
</div>
<div id="right"></div>
</div>
<div id="footer">
<?php
require 'conn/foot.php';
?>
</div>
</body>
</html>
------解决思路----------------------
保存到SESSION
------解决思路----------------------
session   可以
------解决思路----------------------

<?php
session_start(); // 開啓session
ob_clean();
for($i=0;$i<4;$i++){
$num.=dechex(rand(0,15));
}
$num=substr($num,-4,4);
$_SESSION['captcha'] = $num; // 把驗證碼寫入session
$nowimage=imagecreate(100,30);
imagecolorallocate($nowimage,240,240,240);
for($i=0;$i<strlen($num);$i++){
$font=mt_rand(3,5);
$x=mt_rand(1,8)+100*$i/4;
$y=mt_rand(1,50/4);
$color=imagecolorallocate($nowimage,rand(0,150),rand(0,150),rand(0,150));
imagestring($nowimage,$font,$x,$y,$num[$i],$color);
}
for($i=0;$i<200;$i++){
$randcolor=imagecolorallocate($nowimage,rand(200,255),rand(200,255),rand(200,255));
imagesetpixel($nowimage,rand()%70,rand()%20,$randcolor);
}
header("content-type:image/png");
imagepng($nowimage);
imagedestroy($nowimage);
?>


加了兩句
session_start();
$_SESSION['captcha'] = $num;

驗證頁面
session_start();
if($captcha == $_SESSION['captcha']){  // $captcha為用戶提交的驗證碼
    // pass
}else{
    // not match
}
------解决思路----------------------
index.php 先于 verficode.php 执行,慢一步是正常的
所以 zf 采用了保存验证码图片的方案
前几天才在这里讨论过,你可找一下
  相关解决方案