多一行 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>

參考 How to CSRF protect all your forms

Related posts 相關文章
WordPress 6.3 以後可能不支援 PHP 5,最低需求為 PHP 7.4
More...
你的 WordPress 升級到 PHP 8 了嗎
More...
你看 WordPress 也建議至少 PHP 7.4+ 了
More...
PHP 7 最後一版,今年也要退場了
More...

作者

留言

撰寫回覆或留言

發佈留言必須填寫的電子郵件地址不會公開。