14

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.

4
  • 2
    you upload this project on live server recently? If so, then clear everyting php artisan config:clear , php artisan route:clear , php artisan view:clear , php artisan cache:clear then try again. I faced the same problem, after found that my liver server still using my local cache files, which i used fin development server Commented Jul 18, 2020 at 10:05
  • 1
    The session is loaded by reading the session cookie and finding the session with the corresponding session id. If the cookie is not sent or contains a session id that expired then a new session is created. I would take a look at how the session cookie looks like first of all Commented Jul 18, 2020 at 10:09
  • I just realized that every reload, which means a new request, a new token is generated. I realized that by inspecting the meta element that has the csrf token. This only happens in the live server. How can i sort that? What could be the issue considering that it is working fine locally? Commented Jul 18, 2020 at 10:23
  • Does this answer your question? Laravel 5.4 Token Mismatch Exception on live server Commented Nov 10, 2022 at 16:46

7 Answers 7

24

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.

Sign up to request clarification or add additional context in comments.

3 Comments

but what dould be the proble? i had a same issue on my server laravel project
The problem can be something like spaces or line breaks at the very beginning of your php files before you even start the php tags or something more similar to this. This perhaps results in the error as in the question. For more detail information, you can research on why ob_start is used at the very beginning of the php files.
I've worked more then 30 laravel project but this issue was unreachable to me, I also spent 2, 3 days to figuring out the solution for my friends project and finally got project working by this solution, I know this is not a valid solution, but unable to find the exact problem in code.
5

Add the following line to the head tag.

<meta name="csrf-token" content="{{ csrf_token() }}"> // Add in <head></head>

Then get you can get this content attribute in Laravel. Also, in your script tag, add the following code (this is to make sure when you submit the form, you get the correct csrf_token).

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

Comments

3

I had this very same problem, receiving the "CSRF Token Mismatch" exception in Laravel 7, having fixed everything else, like setting the csrf token on page header, in ajax requests, clearing the cache, anything you can think of and usually find in solution proposals.

So, if anyone ever runs into this, I haven't found this solution anywhere else, and it really cost me hours.

I had called the application on the wrong URL!

I used my local IP literally, instead of using the word "localhost".

So, if you're developing locally, calling you app with your IP, try calling it on http://localhost!

1 Comment

Thank you – this was really helpful! In my case, wthe culprit was the redundant trailing forward slash in APP_URL in .env file!
2

Sometimes the "CSRF token mismatch" error appears in the program for other reasons. For example, I received this error when I wanted to upload a very large file (about 1G). When I tested with a smaller file, the program worked fine. To solve the problem, go to the file

app/Http/Kernel.php

and temporarily disable the VerifyCsrfToken middleware (from the $middlewareGroups section). Then test again. Probably the error will change.

In my case, the problem was that the permission of that file was wrong and actually the server had no problem!

Don't forget to re-enable VerifyCsrfToken middleware after the problem is solved.

Comments

1

I faced this issue. I found the solution in Laravel document itself.

We can add $csrf after the form element

<form method="POST" action="/profile">
@csrf

  //input fields here
</form>

1 Comment

@csrf helps to resolve the CSRF token mismatch
0

Unlike @cslotty, in my case I actually had to change my URL from 'localhost' to '127.0.0.1' for it to work. My frontend is in React and the backend in Laravel 8.

Comments

0

If you are using layout extend meta section from the layout.

  1. In your main layout file (e.g., layouts/app.blade.php), define a section for meta tags in the section

    @yield('meta')
  2. Extend the Layout in Your View

    @extends('layouts.app') @section('title', 'Custom Page Title') @section('meta') @endsection

  3. Add headers to the Ajax parameter to carry the csrf token

    $.ajax({ url: '{{ route('route_name') }}', method: 'post', data: formData, contentType : false, processData : false, headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.