多一行 hidden 的 input,然後 value 給個 hash 值,在 POST 動作後,驗證 session 裡的值與 POST 的值是否相同
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
//Here we parse the form
if(!isset($_SESSION['csrf']) || $_SESSION['csrf'] !== $_POST['csrf'])
throw new RuntimeException('CSRF attack');
//Do the rest of the processing here
}
//Generate a key, print a form:
$key = sha1(microtime());
$_SESSION['csrf'] = $key;
?>
<form action="this.php" method="post">
<input type="hidden" name="csrf" value="" />
<!-- Some other form fields you want here, and of course a submit button -->
</form>
留言