PHP
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions
-
Section 4: Object-Oriented PHP
-
Section 5: Working with Data
-
Section 6: Modern PHP (PHP 8)
-
Section 7: Working with Files and Networking
-
Section 8: Common PHP Frameworks Overview
-
Section 9: Tooling and Ecosystem
-
Section 10: Practical Projects
-
Section 11: Interview Practice
-
Section 12: More Standard Library
-
Section 13: Data Structures and Algorithms in PHP
-
Section 14: More Practice Exercises
-
Section 15: More Security and Best Practices
-
Section 16: More Testing and Tooling
-
Section 17: WordPress-Style CMS Concepts
-
Section 18: Advanced OOP Practice
-
Section 19: More Web Fundamentals
-
Section 20: Database Practice
-
Section 21: PHP Manual: Array Functions
-
Section 22: PHP Manual: Date and Calendar Functions
-
Section 23: PHP Manual: Filesystem and Directory Functions
-
Section 24: PHP Manual: Filter and Var Handling
-
Section 25: PHP Manual: Math Functions
-
Section 26: PHP Manual: JSON and XML
-
Section 27: PHP Manual: Network and Stream Functions
-
Section 28: PHP Manual: Error and Exception Handling
-
Section 29: PHP Manual: Output Control and Misc
-
Section 30: PHP Manual: FTP, Zip, and Mail
-
Section 31: Modern PHP Frameworks Deep Dive
-
Section 32: PHP Design Patterns
-
Section 33: More Practice Exercises
-
Section 34: PHP Performance and Deployment
-
Section 35: More Interview Practice
-
Section 36: More PHP Standard Library
-
Section 37: PHP Concurrency and Async
-
Section 38: More Web Development Practice
-
Section 39: PHP Testing Deep Dive
-
Section 40: Composer and Package Development
-
Section 41: PHP Security Deep Dive
-
Section 42: More Practical Projects
-
Section 43: Legacy PHP Maintenance
-
Section 44: More Algorithm Practice
-
Section 45: Final Practice and Review
-
Section 46: PHP for E-Commerce Patterns
-
Section 47: PHP API Design Deep Dive
-
Section 48: PHP Caching Strategies
-
Section 49: PHP Queue and Background Jobs
-
Section 50: PHP Multi-Tenancy Patterns
-
Section 51: PHP Real-Time Features
-
Section 52: PHP CMS and Content Modeling
-
Section 53: PHP Internationalization
-
Section 54: More Framework-Specific Practice
-
Section 55: PHP Legacy Code Refactoring
-
Section 56: More Practice Projects Round 2
-
Section 57: PHP Command-Line Applications
-
Section 58: PHP and Microservices
-
Section 59: More Interview and Review Round 2
66: CSRF Protection Techniques
A few years ago, I worked with a developer who had built a sleek, one-click "Delete Account" feature for a member portal. He’d tested it thoroughly—clicked the button, saw the account vanish, and felt proud of the efficiency. But a week after launch, users started reporting that their accounts were disappearing spontaneously. It turned out a disgruntled former member had posted a hidden image tag on a popular community forum. The src attribute of that image wasn't a picture at all; it was a URL pointing directly to the portal's delete_account.php script. Because the users were already logged into the portal in another tab, their browsers automatically attached their session cookies to the request. The server saw a valid session, assumed the user wanted to delete their account, and complied. The developer hadn't written a single bug in his logic—he had just forgotten that the browser is far too helpful for its own good.
The Mechanical Flaw of Cookies
The core of the problem is that browsers are designed to send all cookies associated with a domain every time a request is made to that domain, regardless of where that request originated. If you are logged into your-bank.com and you visit evil-site.net, that malicious site can trigger a POST request to your bank. Since your browser holds the session cookie for the bank, it attaches it to the request. To the server, this looks like a legitimate action performed by you.
This is why we can't rely on session cookies alone to prove intent. We need a way to verify that the request was actually initiated from our own frontend, not a hidden form on some random corner of the web.
Implementing a Cryptographic Handshake
The most reliable way to stop this is the Synchronizer Token Pattern. Essentially, we generate a unique, random string for the user's session and require that this string be sent back with every state-changing request (POST, PUT, DELETE). If the token in the request doesn't match the one in the session, we kill the request immediately.
// Generating the token and storing it in the session
if (empty($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$token = $_SESSION['csrf_token'];
// In your HTML form
echo '';
When the form is submitted, your verification logic should look something like this:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
// This is a potential CSRF attack
http_response_code(403);
die('Invalid CSRF token');
}
// Proceed with the actual logic (e.g., updating a password)
}
I used hash_equals() here instead of a standard == comparison. This is a small but vital detail: hash_equals is timing-attack safe. It prevents an attacker from guessing the token by measuring how long the server takes to reject a wrong answer.
Adding Layers with SameSite Cookie Attributes
While tokens are the gold standard, modern browsers have introduced a powerful defense-in-depth mechanism: the SameSite attribute for cookies. By setting this attribute, you tell the browser whether it's okay to send the cookie when the request comes from a different site.
You have three main options: Strict, Lax, and None. I almost always recommend Lax for general applications. It prevents the cookie from being sent on cross-site POST requests (the primary CSRF vector) but still allows the cookie to be sent when a user clicks a link from an external site to yours, so they don't arrive at your landing page logged out.
// Setting a session cookie with SameSite=Lax
session_set_cookie_params([
'lifetime' => 0,
'path' => '/',
'domain' => $_SERVER['HTTP_HOST'],
'secure' => true, // Only send over HTTPS
'httponly' => true, // Prevent JavaScript access
'samesite' => 'Lax' // The CSRF defense
]);
session_start();
Don't treat SameSite as a replacement for tokens, though. Older browsers don't support it, and some edge cases can still leave you vulnerable. Think of it as a seatbelt—it's a great safety measure, but you still need a sturdy car (your tokens) to survive the crash.
📋 Practical Task
Exercise: Securing a User Profile Update Form against Cross-Site Forgery
You are provided with a simple PHP page that allows a user to update their email address. Currently, it only checks if the user is logged in, making it vulnerable to CSRF.
Your Task:
- Modify the script to generate a secure, random CSRF token and store it in the
$_SESSIONupon page load. - Inject this token into the email update form as a hidden input field.
- Implement a verification check at the top of the POST processing logic that uses
hash_equals()to validate the submitted token against the session token. - Configure the session cookie settings using
session_set_cookie_paramsto include theSameSite=Laxattribute. - Ensure that if the token is missing or invalid, the script terminates with a
403 Forbiddenheader.
There are no comments for now.