时间:2021-07-01 10:21:17 帮助过:13人阅读
- <br><!--?php <BR-->class Crumb { <br>CONST SALT = "your-secret-salt"; <br>static $ttl = 7200; <br>static public function challenge($data) { <br>return hash_hmac('md5', $data, self::SALT); <br>} <br>static public function issueCrumb($uid, $action = -1) { <br>$i = ceil(time() / self::$ttl); <br>return substr(self::challenge($i . $action . $uid), -12, 10); <br>} <br>static public function verifyCrumb($uid, $crumb, $action = -1) { <br>$i = ceil(time() / self::$ttl); <br>if(substr(self::challenge($i . $action . $uid), -12, 10) == $crumb || <br>substr(self::challenge(($i - 1) . $action . $uid), -12, 10) == $crumb) <br>return true; <br>return false; <br>} <br>} <br> <br>代码中的$uid表示用户唯一标识,而$ttl表示这个随机串的有效时间。 <br> 应用示例 <br> 构造表单 <br> 在表单中插入一个隐藏的随机串crumb <br><span><u></u></span> 代码如下:<pre class="brush:php;toolbar:false layui-box layui-code-view layui-code-notepad"><ol class="layui-code-ol"><li><br> <br> <br>处理表单 demo.php <br> 对crumb进行检查 <br><span><u></u></span> 代码如下:<pre class="brush:php;toolbar:false layui-box layui-code-view layui-code-notepad"><ol class="layui-code-ol"><li><br><!--?php <BR-->if(Crumb::verifyCrumb($uid, $_POST['crumb'])) { <br>//按照正常流程处理表单 <br>} else { <br>//crumb校验失败,错误提示流程 <br>} <br>?> <br> </li></ol></pre></li></ol></pre>