Table of Contents
Generate and Use CSRF Tokens
Regenerate Tokens After Use
Validate Request Origins (Optional but Helpful)
Use SameSite Cookies
Home Backend Development PHP Tutorial How to prevent Cross-Site Request Forgery (CSRF) attacks in PHP?

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

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.

The above is the detailed content of How to prevent Cross-Site Request Forgery (CSRF) attacks in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to get POST data in PHP? How to get POST data in PHP? Sep 16, 2025 am 01:47 AM

Use the $_POST hyperglobal array to obtain POST data, read the value through the form name attribute, and use a foreach loop when processing array input, so that the data needs to be verified and filtered to prevent XSS.

Aisi Assistant's genuine download portal_Aisi Assistant's iPhone installation link Aisi Assistant's genuine download portal_Aisi Assistant's iPhone installation link Sep 16, 2025 am 11:30 AM

The official download portal of Aisi Assistant is located on the official website https://www.i4.cn/, and provides computer and mobile downloads, supporting device management, application installation, mode switching, screen projection and file management functions.

How to prevent XSS (Cross-Site Scripting) attacks in PHP? How to prevent XSS (Cross-Site Scripting) attacks in PHP? Sep 15, 2025 am 12:10 AM

PreventXSSbyescapingoutputwithhtmlspecialchars()orjson_encode(),validatinginputusingfilter_var(),applyingCSPheaders,andusingsecureframeworkslikeLaravel.

How to get the request method (GET, POST, PUT) in PHP? How to get the request method (GET, POST, PUT) in PHP? Sep 16, 2025 am 04:17 AM

Use $_SERVER['REQUEST_METHOD'] to obtain HTTP request methods, such as GET, POST, PUT, DELETE; for PUT and other methods, you need to read the original data through file_get_contents('php://input'), and use the switch statement to process different request types.

How to convert an object to an array in PHP? How to convert an object to an array in PHP? Sep 14, 2025 am 03:14 AM

Use (array) to convert simple objects into arrays. If they contain private or protected properties, the key names will have special characters; for nested objects, recursive functions should be used to traverse the conversion to ensure that all hierarchical objects become associative arrays.

How to add a watermark to an image in php How to add a watermark to an image in php Sep 15, 2025 am 03:26 AM

Use PHP's GD library to add watermarks to images. First load the original image and watermark (text or image), then use imagecopy() or imagettftext() to merge, and finally save the output. Support JPEG, PNG and other formats, pay attention to handling transparency and font paths, and ensure that GD extension is enabled.

How to work with environment variables in PHP? How to work with environment variables in PHP? Sep 15, 2025 am 03:55 AM

Usegetenv()toreadenvironmentvariablesandvlucas/phpdotenvtoload.envfilesindevelopment;storesensitivedatalikeAPIkeysoutsidecode,nevercommit.envtoversioncontrol,anduseactualenvironmentvariablesinproductionforsecurity.

How to make an API call using cURL in PHP? How to make an API call using cURL in PHP? Sep 15, 2025 am 05:16 AM

InitializecURLwithcurl_init(),setoptionslikeURL,method,andheaders,senddatausingPOSTorcustommethods,handleresponseviacurl_exec(),checkerrorswithcurl_error(),retrievestatususingcurl_getinfo(),decodeJSONresponse,andclosewithcurl_close().

See all articles