一个简单的php验证码实例,仅用参考和理解, 验证输入文件verify.php 和 验证结果文件verify2.php,如下
verify.php
<?php $str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; //数字和字母验证码 $str2 = 'ABCDEF0123456789'; //用于验证码字符,十六进制颜色 $captcha=''; //验证码初始值
//随机获取4个字符的验证码 for ($i=0; $i < 4; $i++) { $color = '#'; for ($j=0; $j < 6; $j++) { $color.=$str2{mt_rand(0,strlen($str2)-1)}; }
$captcha .= '<span style="color:'.$color.'">'.$str{mt_rand(0,strlen($str)-1)}.'</span>'; }
//输出显示带方框的验证码 echo '<span style="200px;heifht:60px;border:3px solid #666;font-size:40px;">'.$captcha.'</span>';
$captcha = strip_tags($captcha); //去除html标签,去除颜色,留下纯字符 echo "<br/>"; echo "<br/>"; echo "<br/>";
/* 验证码输入框
* 设置一个hidden标签储存验证码的值
* 用post方法将验证码的值与输入的值传到verify2.php去比较验证
*/ echo<<<EOF <form action="verify2.php" method="post"> <input name="verify" /> <input type="hidden" name="captcha" value="{$captcha}" /> <input type="submit" value="Verify"/> </form> EOF; ?>
verify2.php
<?php
// 将获取到验证码的值与输入的值都转化为小写,并用php内置函数srim()去除左右空格 $verify = trim(strtolower($_POST['verify'])); $verify2 = trim(strtolower($_POST['captcha']));
//判断输入是否为空
if (!isset($verify) || $verify == '') { exit('null..<a href="verify.php">try again<a/>'); }
//判断验证码输入是否成功 if ($verify == $verify2) { echo "success!"; }else exit('wrong..<a href="verify.php">try again<a/>'); ?>