目次
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 中国語 Web サイトの他の関連記事を参照してください。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Stock Market GPT

Stock Market GPT

AIを活用した投資調査により賢明な意思決定を実現

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

PHPでのクロスサイトリクエストフォーファリー(CSRF)攻撃を防ぐ方法は? PHPでのクロスサイトリクエストフォーファリー(CSRF)攻撃を防ぐ方法は? Sep 11, 2025 pm 12:45 PM

ThemoStecteftectivetewwaytopreventcsrfattacksinphpisusanti-csrftokens.generateasecuretokenviabin2hex(random_bytes(32))、storeitin $ _ session、andincludeitahiddiddidenfieldinfieldinforms.uponsforms.uponsubmision、dectokenmateSesessionvento;

PHPの画像に透かしを追加する方法 PHPの画像に透かしを追加する方法 Sep 15, 2025 am 03:26 AM

PHPのGDライブラリを使用して、画像に透かしを追加します。最初に元の画像と透かし(テキストまたは画像)をロードし、次にimageCopy()またはImagetTftext()を使用してマージし、最後に出力を保存します。 JPEG、PNG、その他の形式をサポートし、透明性とフォントパスの処理に注意し、GD拡張機能が有効になっていることを確認してください。

PHPで区切り文字で文字列を分割する方法は? PHPで区切り文字で文字列を分割する方法は? Sep 11, 2025 pm 12:58 PM

exploit()関数を使用して文字列をセパレーターで分割し、その構文はexplore( "、"、 "、" apple、banana ")などのexplore(delimiter、string、lime number)です。 LIMITパラメーターは、Explore( " - "、 "One-tw-three"、2)などの返された要素の数を制御して['one'、 '2-three']を取得できます。複数のセパレータが必要な場合、preg_split()などのpreg_splitなどの正規表現でpreg_split()が使用されます

PHPでCurlを使用してAPI呼び出しを作成する方法は? PHPでCurlを使用してAPI呼び出しを作成する方法は? Sep 15, 2025 am 05:16 AM

intializecurlwithcurl_init()、setoptionslikeurl、method、andheaders、senddatausingpostorcustomtometods、handleresponseviacurl_exec()、checkerrorswithcurl_error()、retievestatususingcurl_getinfo()、decodejsonrespurlletosons(

PHPでオブジェクトを配列に変換する方法は? PHPでオブジェクトを配列に変換する方法は? Sep 14, 2025 am 03:14 AM

(配列)を使用して、単純なオブジェクトを配列に変換します。プライベートまたは保護されたプロパティが含まれている場合、キー名に特殊文字があります。ネストされたオブジェクトの場合、再帰関数を使用して変換を横断して、すべての階層オブジェクトが連想配列になるようにする必要があります。

PHPでXSS(クロスサイトスクリプト)攻撃を防ぐ方法は? PHPでXSS(クロスサイトスクリプト)攻撃を防ぐ方法は? Sep 15, 2025 am 12:10 AM

preventXsssssbyescapingOutputwithhtmlspecialChars()orjson_encode()、validatinginputusingfilter_var()、applyingcspheaders、andusingsingsecureframeworkslikelaravel。

PHPで投稿データを取得する方法は? PHPで投稿データを取得する方法は? Sep 16, 2025 am 01:47 AM

$ _POST HyperGlobal Arrayを使用してPOSTデータを取得し、フォーム名属性を使用して値を読み取り、配列入力を処理するときにForeachループを使用して、XSSを防ぐためにデータを検証およびフィルタリングする必要があります。

PHPで環境変数を操作する方法は? PHPで環境変数を操作する方法は? Sep 15, 2025 am 03:55 AM

usegetEnv()toreadenvironmentvariablesandvlucas/phpdotenvtoload.envfilesindevelopment; storeSensitalikeapikeysoutsidecode、nevercommit.envtoversion control、およびuseatualenvironmentvariablesininininporursecurity。

See all articles