1.原理
数组中每个图片对应一个值->随机值->获取并保存到$_SESSION中,->获取随机值对应的图片,->通过__FILE__输出图片,->浏览器验证
2.代码
captcha.php
<?php session_start(); //图片对应 $picArray = array( ‘pic00‘=>‘狗‘, ‘pic01‘=>‘猫‘, ‘pic02‘=>‘鱼‘, ‘pic03‘=>‘鸟‘ ); //随机取值 $index = mt_rand(0,3); $value = $picArray[‘pic0‘.$index]; $_SESSION[‘authcode‘] = $value; $filename = dirname(__FILE__).‘./img/pic0‘.$index.‘.jpg‘; //echo $filename; $content = file_get_contents($filename); header(‘Content-type: image/jpg‘); echo $content;
form.php
<?php if (isset($_REQUEST[‘authcode‘])) { session_start(); //判断 if (strtolower($_REQUEST[‘authcode‘] == strtolower($_SESSION[‘authcode‘]))) { echo ‘恭喜你输入正确!‘; } else { echo ‘输入失败!‘; } exit(); } ?> <html> <head> <title>验证码提交</title> </head> <body> <form action="form.php" method="post"> <p>验证码:<img src="captcha.php?r=<?php echo mt_rand() ?>" id="captcha_img" alt="验证码" width="200" height="200" border="1px"></p> <a href="javascript:void(0)" onclick="document.getElementById(‘captcha_img‘).src=‘./captcha.php?r=‘+Math.random()">看不清?</a> <p> <label for="authcode">请输入图片中的内容: </label> <input type="text" name="authcode" id="authcode"/> </p> <p><input type="submit" value="submit"/></p> </form> </body> </html>
时间: 2024-12-11 18:32:45