zoukankan      html  css  js  c++  java
  • PHP 表单添加隐藏 Token 阻止外部提交

    Token 法:通过一个隐藏可变的 Token 加大攻击的难度,每次提交都需要和服务器校对,如果不通过,则为外部提交(也可以通过 session + 隐藏域来验证)。

    代码:

    form.php

     1 <!DOCTYPE html>
     2 <html lang="en">
     3 <head>
     4     <meta charset="UTF-8">
     5     <title>Document</title>
     6 </head>
     7 <body>
     8     <?php 
     9         define('SECRET', "67%$#ap28");
    10         function m_token() {
    11             $str = mt_rand(1000, 9999);
    12             $str2 = dechex($_SERVER['REQUEST_TIME'] - $str);
    13             return $str.substr(md5($str.SECRET), 0, 10).$str2;
    14         }
    15     ?>
    16     <form action="dopost.php" method="post">
    17         name:<input type="text" name="name" id="">
    18         <input type="hidden" name="token" value="<?php echo m_token();?>">
    19         <input type="submit" value="提交">
    20     </form>
    21 </body>
    22 </html>

    dopost.php

    <?php
    define('SECRET', "67%$#ap28");
    
    function v_token($str, $delay = 2) {
        $rs = substr($str, 0, 4);
        $middle = substr($str, 0, 14);
        $rs2 = substr($str, 14, 8);
        return ($middle == $rs.substr(md5($rs.SECRET), 0, 10)) 
                && ($_SERVER['REQUEST_TIME'] - hexdec($rs2) - $rs <= $delay);
    }
    var_dump(v_token($_POST['token']));

    其中 $delay 表示时间延迟,在不同的程序根据根据业务来自行修改

    输出:

    boolean true
  • 相关阅读:
    learning scala view collection
    scala
    learning scala dependency injection
    learning scala implicit class
    learning scala type alise
    learning scala PartialFunction
    learning scala Function Recursive Tail Call
    learning scala Function Composition andThen
    System.Threading.Interlocked.CompareChange使用
    System.Threading.Monitor的使用
  • 原文地址:https://www.cnblogs.com/dee0912/p/4909769.html
Copyright © 2011-2022 走看看