


How to prevent Cross-Site Request Forgery (CSRF) attacks in PHP?
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.
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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.

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.

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

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.

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.

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.

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

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