How to Create CSRF Protection Token in PHP – A Step-by-Step Guide!

Опубликовано: 28 Март 2026
на канале: LinuxHowTo
111
0

Want to secure your PHP forms against CSRF attacks? In this video, we’ll show you how to create and use a CSRF protection token. Cross-Site Request Forgery (CSRF) is an attack where a malicious site tricks a user’s browser into sending unauthorized requests to a trusted site, exploiting user credentials. This tutorial demonstrates how to secure a PHP form with a CSRF token to ensure requests come from your site. Follow along with our detailed guide to implement CSRF protection in your PHP forms!

Learn:
What is CSRF?
Cross-Site Request Forgery (CSRF) is an attack where a malicious site tricks a user’s browser into sending unauthorized requests to a trusted site, exploiting user credentials. This tutorial shows how to secure a PHP form with a CSRF token to ensure requests come from your site.
Steps to Implement CSRF Protection

1. Start a Session
Use session_start() to enable session storage for the CSRF token.

2. Generate Secure Token
Create a random 32-byte token with random_bytes(), convert to hex with bin2hex(), and store it in $_SESSION['csrf_token'].

3. Add Token to Form
Embed the token in a hidden input field in an HTML form alongside other inputs (e.g., a name field).

4. Validate on Submission
On POST, use hash_equals() to compare $_POST['csrf_token'] with $_SESSION['csrf_token']. Reject missing or invalid tokens.

5. Process Valid Form
If valid, process form data (e.g., sanitize input) and clear the token with unset($_SESSION['csrf_token']).

Example Code
You can find the complete example code on GitLab: https://gitlab.com/hatem-badawi/linux....

Testing
Save the Script: Save the script as csrf_form.php on a PHP server (e.g., http://localhost/csrf_form.php).
Submit the Form: It should display “Hello, [name]!”.
Test CSRF: Submit without a valid token (e.g., via curl); it should fail with “CSRF token invalid!”.

curl -X POST -d "name=TestUser" http://localhost/csrf_form.php

✅ Why It Works
Random Token: A 32-byte token is unguessable and session-specific.
Secure Comparison: hash_equals() prevents timing attacks.
Single-Use: The token is cleared after use.
Malicious Sites Blocked: They can’t provide the correct token.

✅ Best Practices
Use HTTPS: Secure token transmission.
Sanitize Inputs: Use htmlspecialchars() to prevent XSS.
Frameworks: For larger apps, use frameworks like Laravel with built-in CSRF protection.

GitLab Link
You can find the complete example code and tutorial PDF at this GitLab link: https://gitlab.com/hatem-badawi/linux....

Hit subscribe for more PHP tips and like if this helped.
Let us know: What security feature will you implement next in your PHP forms?

👉 Watch now and secure your PHP forms against CSRF attacks!

#PHP #CSRFProtection #WebSecurity #FormSecurity #LinuxTips

(Short, clear, and packed with practical knowledge!)