PHP: Adding CSRF protection is super easy!

Published on Author Yani2 Comments

Adding CSRF protection to a PHP script is really easy once you understand how and what it should be doing. You can look at CSRF protection like a pre-filled captcha, which adds a layer of protection as it can’t just be generated by somebody and match the one we have on the server.

I have written a class that makes it even easier. The only thing that’s really happening is that we’re making a token and putting it in a session. We then put the token in a hidden input in the form, so it gets sent in our POST request. Because the token is in the session, we just have to check if the posted token matches the one in our session.

This whole method of protection is called CSRF protection, as it makes it for attackers a lot harder to submit a form in the background, as they will have to send the correct token with it.


Here’s a very simple class that should work perfectly fine in every situation.

class CSRF
    public function __construct(){
    public function create()
        return $_SESSION['csrf'] = substr(sha1(microtime() . session_id()), 0, 12);
    public function verify()
        if (isset($_POST['csrf']) && isset($_SESSION['csrf'])
        && is_string($_POST['csrf']) && $_POST['csrf'] == $_SESSION['csrf']) {
            return true;
        } else {
            return false;
    public function __toString()
       return '<input type="hidden" name="csrf" value="' .$this->create(). '" />';


The usage is very simple. In your login logic, you would just have something like this:

$csrf = new CSRF();

  die('Invalid CSRF token');
} else {
  // Do login


An then in your form, you can simply add the hidden input like so:

echo $csrf;


And that’s it, your form is now protected from CSRF and it was super easy.



Oh and I have also made a gist of this scrip, in case you want to push some updates:



2 Responses to PHP: Adding CSRF protection is super easy!

  1. Humm, this means:
    You can only have one form or action at a time. While most advanced websites have many, as next page load (multiple tabs or multiple ajax calls) you would lose your functionality.

    In itself it would also require an origin lock in the headers, else I can load your website from an other website your not knowing visitor is tricked to visit and loads your form using javascript and get your csrf key and your security fails.

    • You’re totally right. I’ve actually fixed all of this for my personal projects.

      In this post I wanted to make it as simple as possible, which actually made it unsafe, and not good overall.

      I’ll leave the post up for a while longer, and probably delete it soonish.

Leave a Reply

Your email address will not be published. Required fields are marked *