目錄
Generate and Use CSRF Tokens
Regenerate Tokens After Use
Validate Request Origins (Optional but Helpful)
Use SameSite Cookies
首頁 後端開發 php教程 如何防止PHP中的跨站點偽造(CSRF)攻擊?

如何防止PHP中的跨站點偽造(CSRF)攻擊?

Sep 11, 2025 pm 12:45 PM
php csrf

The most effective way to prevent CSRF attacks in PHP is using anti-CSRF tokens. Generate a secure token via bin2hex(random_bytes(32)), store it in $_SESSION, and include it as a hidden field in forms. Upon submission, verify the token matches the session value; reject mismatches. Regenerate tokens after sensitive actions to prevent replay attacks. Optionally, check $_SERVER['HTTP_REFERER'] to confirm request origin, but don’t rely on it alone. Set SameSite=Strict or Lax for session cookies using session_set_cookie_params(['samesite' => 'Strict']) to limit cross-site cookie transmission. Combining tokens with SameSite cookies provides robust protection. Always implement CSRF tokens for state-changing operations—critical for security.

How to prevent Cross-Site Request Forgery (CSRF) attacks in PHP?

To prevent Cross-Site Request Forgery (CSRF) attacks in PHP, the most effective method is to use anti-CSRF tokens. These tokens ensure that requests sent to your server originate from your own application and not from a third-party site.

Generate and Use CSRF Tokens

Each time a form is displayed, generate a unique, cryptographically secure token and store it in the user’s session. Include this token as a hidden field in the form. When the form is submitted, verify that the submitted token matches the one stored in the session.

  • Generate a token using random_bytes() or bin2hex(random_bytes(32)) for uniqueness and security.
  • Store the token in $_SESSION with a user-specific key.
  • Add the token as a hidden input: .
  • On form submission, compare the POST value with the session-stored token. Reject the request if they don’t match.

Regenerate Tokens After Use

For higher security, especially after sensitive operations like password changes or payments, regenerate and invalidate old tokens. This prevents token replay attacks.

  • After successfully processing a request, remove the old token from the session.
  • Generate a new token for the next form or action.

Validate Request Origins (Optional but Helpful)

Check the HTTP Referer header to ensure the request came from your domain. While not foolproof (the header can be missing or spoofed), it adds an extra layer.

  • Use $_SERVER['HTTP_REFERER'] cautiously.
  • Compare it against your allowed domains, but don’t rely on it as the sole protection.

Use SameSite Cookies

Set the SameSite attribute on your session cookies to Strict or Lax. This helps browsers block sending cookies during cross-site requests, reducing CSRF risk.

  • Configure in PHP: session_set_cookie_params(['samesite' => 'Strict']);
  • Or set via php.ini: session.cookie_samesite = Strict

Combining CSRF tokens with SameSite cookies provides strong protection. Tokens handle form integrity, while SameSite restricts cookie transmission in cross-origin contexts. Basically, always use tokens for state-changing actions—CSRF protection is simple to implement and critical for security.

以上是如何防止PHP中的跨站點偽造(CSRF)攻擊?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Stock Market GPT

Stock Market GPT

人工智慧支援投資研究,做出更明智的決策

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

如何在PHP中獲取發布數據? 如何在PHP中獲取發布數據? Sep 16, 2025 am 01:47 AM

使用$_POST超全局數組獲取POST數據,通過表單name屬性讀取值,處理數組輸入時用foreach循環,需驗證和過濾數據防止XSS。

愛思助手正版下載入口_愛思助手iPhone安裝鏈接 愛思助手正版下載入口_愛思助手iPhone安裝鏈接 Sep 16, 2025 am 11:30 AM

愛思助手正版下載入口在官網https://www.i4.cn/,提供電腦端和手機端下載,支持設備管理、應用安裝、模式切換、屏幕投射及文件管理等功能。

如何防止PHP中的XSS(跨站點腳本)攻擊? 如何防止PHP中的XSS(跨站點腳本)攻擊? Sep 15, 2025 am 12:10 AM

dextxssbyescapingOutputwithHtmlSpecialChars()orjson_encode(),varyatingInputingFilter_var(),ApplivingCspheaders,andusingsecureframeworkslikelaravel。

如何在PHP中獲取請求方法(獲取,發布,放置)? 如何在PHP中獲取請求方法(獲取,發布,放置)? Sep 16, 2025 am 04:17 AM

使用$_SERVER['REQUEST_METHOD']可獲取HTTP請求方法,如GET、POST、PUT、DELETE;對於PUT等方法需通過file_get_contents('php://input')讀取原始數據,並可用switch語句處理不同請求類型。

如何將對象轉換為PHP中的數組? 如何將對象轉換為PHP中的數組? Sep 14, 2025 am 03:14 AM

使用(array)可將簡單對象轉為數組,若含私有或受保護屬性,鍵名會帶特殊字符;對於嵌套對象,應使用遞歸函數遍歷轉換,確保所有層級對像變為關聯數組。

如何在PHP中的圖像中添加水印 如何在PHP中的圖像中添加水印 Sep 15, 2025 am 03:26 AM

使用PHP的GD庫可為圖片添加水印。首先加載原圖和水印(文字或圖像),再用imagecopy()或imagettftext()合併,最後保存輸出。支持JPEG、PNG等格式,注意處理透明度和字體路徑,確保GD擴展已啟用。

如何處理PHP中的環境變量? 如何處理PHP中的環境變量? Sep 15, 2025 am 03:55 AM

useeDenVoriablesandAndVlucas/phpdotenvtoload.envfilesIndeplepent; storessensitivedatalikeapikeysoutsidecode,nevercommit.envtoversioncontrol,andeectimentectualenvarionmentvariablesinblesinprododroductorityforsecurity。

如何在PHP中使用Curl進行API調用? 如何在PHP中使用Curl進行API調用? Sep 15, 2025 am 05:16 AM

初始izecurlwithcurl_init(),setOptionsLikeUrl,方法和檯面,senddatausingpostorcustormethods,handleressponseviacurl_exec(),checkerrorswithcurl_error(),retrievestatusatusususestatususingestatususisusiscusiscull_getInfo()

See all articles