php防止CSRF(跨站請求偽造)的原理實現示例


<?php
session_start();

//生成隨機字符串
function randomStr($max = 16){
    $str = 'abcdefghijklmnopqrstuvwxyz'.
           '0123456789'.
           'ABCDEFJHIJKLMNOPQRSTUVWXYZ';
       
    $val = '';
    $str = str_shuffle($str);  //打亂字符串
for($i = 0; $i < $max; $i++){ $val .= $str[rand(0, strlen($str) - 1)]; } return $val; } $retStr = randomStr(); echo '原始的值:'.$_SESSION['token'].'<br>收到的值:'.$_POST['token'].'<br>'; //此函數給URL重寫機制添加名/值對。 //此函數要寫在 html 頁面前端中;如果是 MVC 模式,應包含在 view 視圖文件內 output_add_rewrite_var('token', $retStr); //服務端判斷執行 if(filter_has_var(INPUT_POST, "token") && $_POST['token'] == $_SESSION['token']){ echo '<strong style="color:red">執行代碼了!內容為:'.$_POST['var2'].'</strong>'; } //在程序判斷后才寫進 session 否則數據不一致 $_SESSION['token'] = $retStr; ?> <div> <a href="file.php">link</a> <a href="http://example.com">link2</a> <form action="" method="post"> <input type="text" name="var2" value="這是默認值!"/> <input type="submit" value="確定"> </form> </div> <?php print_r(ob_list_handlers()); ?>

 參考php手冊內容地址:https://www.php.net/manual/zh/function.output-add-rewrite-var.php


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM