How to solve "CSRF Token Mismatch" in Laravel

Issue

I am working on a laravel application. Upon hosting it on my domain, I am running into a "CSRF token mismatch" error. Locally, the application is working fine because I have included the csrf token in the header as shown in the documentation. Therefore, the csrf token is being generated successfully and being included in the header of requests. On doing some debugging, I changed the SESSION_DRIVER in env file to file so that I can see the sessions. I realized that multiple sessions are being generated for one user. The SESSION_LIFETIME is set to 120, which I believe is okay. In looking at the tokens in the sessions stored in storage/framework/sessions, none contains the token that is generated by the browser. What could be the issue? Remember that it is working fine locally. What configurations on the host domain could be affecting the sessions of the application.

Solution

I once ran into the same error while hosting in the cPanel and took me almost 3days to figure out the solution for my case.
I do not know if this works for you but give it a try.

Inside your main index.php file inside the public folder, edit it and at the very top after starting PHP tags, write

ob_start()

This function will take the contents of the output buffer and returns a string that is to be sent to the browser for rendering and removes the spaces or line breaks you put before starting PHP.

Also, try clearing the cache as suggested in the comments.

Let me know if this helps you as well.

Answered By – Meeraj Adhikari

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published