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.
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 サイトの他の関連記事を参照してください。

ホットAIツール

Undress AI Tool
脱衣画像を無料で

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

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

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

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

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

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

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

ホットトピック

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

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

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

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

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

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

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

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