使用php在服务器端生成图文验证码

图文验证码的实现原理:

1):准备些许图片将其存储在数据库,每一张图片对应一个标识字段。

2):在服务器端使用数组的形式将图片与标识字段组合起来。

3):随机给客户端返回图片,并接受用户输入的字段。

4):将用户输入的字段与服务器存储的与每张图片的信息进行比对。

5):相同则通过,否则不通过。

a)第一步生成验证码

createCode.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php
    header("content-type:text/html;charset=utf-8");   
    session_start();//开启服务器 存储
    $table=array(
      'pic0'=>"猫"
      'pic1'=>'狗',
      'pic2'=>'猴',
      'pic3'=>'鱼'
    );
      $index=rand(0,3);//生成随机数
      $value=$table['pic'.$index];//取出随机值
      $_SESSION['authcode']=$value;//将值存储在服务器端
 
      $filename=dirname(__FILE__).'\pic'.$index.'.jpg';//给出文件的地址
        
      $content=file_get_contents($filename);//读取文件的内容
       
      ob_clean();//清除缓存
       
      header("content-type:image/jpg");//规定以jpg的形式输出图片
       
      echo $contents;//输出图片文件
?>

b)使用验证码  

useCode.php: 

1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
    header("content-type:text/html;charset=utf-8");
    if(isset($_REQUEST["authcode"])){
         session_start();    
         if($_SESSION['authcode']==$_REQUEST['authcode']){//$_REQUEST['authcode']..获取输入框的值
             echo "<font>验证通过</font>";
          }
         else{
             echo "<font>验证失败</font>";
         }
         exit();
    }
?>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>验证码正确</title>
</head>
</html>
<body>
    <form action="useCode.php">
       <p>验证码图片:
           <img src="createCode.php?=<?php echo rand();?>
            onclick="this.src='createCode.php?+<?php rand(0,200)?>'"
            alt=""
           ">
       </p>
       <p>输入验证码的内容:
           <input type="text" name="authcode" value="">
       </p>
       <p>
           <input type="submit" value="提交">
       </p>
    </form>   
</body>   

 事实截图:

 

原文地址:https://www.cnblogs.com/zzp0320/p/8080242.html