Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

armen_98's avatar

CSRF not working properly

Hey all! My csrf check is not working as it should. Here what I have: routes.php

Route::get('test', 'test@show');
Route::post('test', 'test@show');

test.php (controller)

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;

class test extends Controller
{
    public function show(Request $request)
    {
        return view('test');
    }
}

test.blade.php

<form action="{{ url('/test') }}" method="POST">
    {{ csrf_field() }}
    <input type="submit">
</form>

When I start hitting Submit button after several succesed submits I get TokenMismatchException. Every time. Any Ideas how to fix this?

0 likes
15 replies
jimmck's avatar

@armen_98 This is a known problem that is fixed by reading the documentation. There is more storage devoted to this topic than what is used at the library of congress.

armen_98's avatar

@jimmck I really tried out to google how to fix this, but I found nothing useful :( Could u give me a link or maybe told me how to google this, please?

jimmck's avatar

@armen_98 So at the top of this page is a well crafted search box and you did not type in csrf and hit return? Just to start? You can spend the rest of today reading about this topic. You can also sign up for a month and watch all of the great videos on Laravel.

Snapey's avatar

If it's any consolation, I currently have 320+ correct answers on this forum and have never seen a reliable answer to this issue that some people seem to suffer with. It should work, as you have it, 100% of the time, with the only exception being if you let the session time out.

eg (all unanswered)

Snapey's avatar

Do you use file based sessions or database?

Try your tests and keep an eye on the sessions folder (storage/framework/session). Do you see a new session being created?

armen_98's avatar

I am using file based sessions.

When the test is successfully passed no new file is being created. But when it fails new file is created and the token there does not match with the form's one. That new file is being created AFTER the submit button is clicked and BEFORE i get the error message, so I think that problem is from Laravel. But anyway, I will try to move my site to web hosting and try there one more time.

jlrdw's avatar

Have you tried to set something in a sesssion as a test to see if it's working as expected. Just a test.

armen_98's avatar

Ok, i tried to test on web hosting and i got no error this time. Also I tried this on another notebook with linux installed on it, and I also got no errors. So I guess this comes from windows, maybe some access troubles.

@jlrdw you mean mannually change the token in the new created file to the right one? Ok, I will try now

armen_98's avatar

@jlrdw when I mannueally changed the token to the old one and refreshed the page - everything worked well. But after a couple of other tests it fails again

jlrdw's avatar

@armen_98 no just test your session on various browsers, I have seen this topic come up many times.

armen_98's avatar

@jlrdw I've tried in chrome, firefox and opera, no matter what browser I am using, after a several tests csrf fails

jlrdw's avatar

In another framework I make my own token

        $data['token'] = Cln::setToken();
        Session::set('token', $data['token']);

function that sets it

public static function setToken($name = 'csrfToken') {
        $csrfToken = md5(uniqid(rand(), TRUE));
        return $csrfToken;
    }

passed to view with a

 ->with('data2', $data['token']);

in view

<input type="hidden" name="token" value="<?php echo $data2; ?>" />

Check in controller

$mytkn = Session::get('token');
            $hastoken = Cln::fixTok($mytkn);
            if ($hastoken == "nocsrf") {
                Session::set('token', md5(uniqid(rand(), TRUE)));  /////// TO SPOOF OF A FAKE ONE COMING THROUGH
            }
            if ($_POST['token'] != Session::get('token')) {
                return Redirect::to('admin');
            }

the function doing the check

public static function fixTok($tosess = null) {
        $tosess = (is_null($tosess) || empty($tosess) || strlen($tosess) < 1 ? 'nocsrf' : trim($tosess));
        return $tosess;
    }

Works like a champ, but get your rocket science degree first. Been using for a while. Oh wait, rocket science not required.

jimmck's avatar

@armen_98 Sir I leave now in the most capable of hands our resident Oracle and seer of all that can be unseen. And be sure to keep your code backward compatible. And try as you might you will never completely synchronize with a server side resource. Sometimes a new token must be used and you can reload the page or create a scheme to get a new one.

https://github.com/GeneaLabs/laravel-caffeine

Snapey's avatar

Sounds like you are starting a new session for some reason. Whether that session file is created after the request might be debatable because of the way Windows refreshes the explorer view (there might be some delay in displaying).

Please or to participate in this conversation.