由于用户可能会从其他途径POST过来,因此我们需要防止这种情况
原理:在页面生成一个随即串并保存在token中,用于在服务器中比对
index.php 与 temp.php 两个页面示范
index.php 页面:
- <pre name="code" class="php"><?php
- session_start();
- $csrf = md5(uniqid(rand(), TRUE));
- $_SESSION['csrf'] = $csrf;
- ?>
- <meta charset="utf-8">
- <form action="temp.php" method="post" name="form1" idf="form1">
- 测试:<input type="text" name="user" id="user">
- <input type="hidden" name="csrf" id="csrf" value="<?php echo $csrf;?>">
- <input type="submit" name="submit" value="提交">
- </form>
- <span style="background-color: rgb(255, 255, 255);">
- </span>
- <span style="background-color: rgb(255, 255, 255);">
- </span>
- <pre name="code" class="php"><?php
- session_start();
- if(isset($_POST['user']) && $_SESSION['csrf'] == $_POST['csrf']){
- echo '测试通过且 csrf:'.$_SESSION['csrf'];
- }else{
- echo '测试失败';
- }