🛡️ PHP Security & Login
Estimated reading: 4 minutes 363 views

PHP CSRF – Protect Your PHP Forms from Cross-Site Request Forgery

Learn how to prevent CSRF attacks in PHP using secure tokens to protect your forms and user actions.


Introduction – What Is PHP CSRF and Why It Matters in PHP?

Cross-Site Request Forgery (CSRF) is a security vulnerability where an attacker tricks a logged-in user into performing unwanted actions on a web application. If a PHP app doesn’t validate where a request is coming from, attackers can forge form submissions or data changes without user consent.

In this guide, you’ll learn:

  • What CSRF is and how it affects PHP applications
  • How to generate and validate CSRF tokens in forms
  • Best practices to protect against CSRF attacks
  • How CSRF differs from XSS

PHP CSRF

The most effective protection against CSRF in PHP is to generate a random token, store it in the session, and include it in every form. On form submission, PHP checks if the token matches the one stored.


CSRF Workflow

  1. A CSRF token is generated on page load and stored in $_SESSION
  2. The token is included in the HTML form as a hidden field
  3. When the form is submitted, PHP compares the submitted token with the session token
  4. If the token is missing or invalid, the request is rejected

Generate a CSRF Token

session_start();

if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

Use bin2hex(random_bytes()) for a cryptographically secure token


HTML Form with CSRF Token

<form method="post" action="submit.php">
  <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
  <input type="text" name="data" required>
  <input type="submit" value="Submit">
</form>

Validate CSRF Token in PHP

session_start();

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        die(" CSRF token mismatch. Request denied.");
    }

    echo " CSRF token valid. Form processed.";
}

Always check if the token exists and matches the one stored in the session


CSRF vs XSS – What’s the Difference?

Attack TypeDescriptionPrevention
CSRFTricked requests using valid credentialsUse CSRF tokens
XSSMalicious scripts injected into web pagesUse htmlspecialchars() on output

Additional Tips for CSRF Protection

  • Use SameSite=Strict or SameSite=Lax on cookies
  • Rotate CSRF tokens per session or request
  • Use HTTPS to prevent token exposure in transit
  • Combine with session management for better security

Summary – Recap & Next Steps

CSRF protection is critical for all PHP applications that handle form submissions or authenticated actions. A simple token system ensures that only genuine users can perform sensitive actions, such as data changes or purchases.

Key Takeaways:

  • CSRF attacks exploit trusted sessions to perform unauthorized actions
  • Use tokens in forms and validate them server-side
  • Store tokens in $_SESSION and check them on POST requests
  • Combine CSRF tokens with SameSite cookies and HTTPS for better protection

Real-World Use Cases:
Login forms, comment systems, checkout pages, user settings, profile updates


Frequently Asked Questions (FAQs)

Is CSRF a problem for GET requests?
Generally, yes if GET requests perform sensitive actions (e.g., /delete?id=1). But best practice is to use POST for all state-changing actions.

Can CSRF tokens be reused?
Yes, unless you regenerate them per request. For higher security, use one-time tokens.

Does PHP provide built-in CSRF protection?
No native support. You must implement CSRF tokens manually or use frameworks like Laravel or Symfony which handle it internally.

Can JavaScript access CSRF tokens?
Only if rendered into the page or stored in a cookie. Don’t expose CSRF tokens via public APIs.

Does using AJAX require CSRF protection?
Absolutely. Any POST request that modifies data should validate a CSRF token — even via AJAX.


Share Now :
Share

🛡️ PHP CSRF

Or Copy Link

CONTENTS
Scroll to Top