mrsimon mrsimon - 3 months ago 17
PHP Question

TokenMismatchException in VerifyCsrfToken.php

I'm getting the error


TokenMismatchException in VerifyCsrfToken.php line 55


When I try to submit a simple email form to

public function postContact(Request $request)
{
// code
}


But it never gets to the code part. So I tried comparing the values in the get method like so:

public function getContact(Request $request)
{
echo $request->session()->token();
return view('contact');
}


Then I compared to the value stored in the hidden field name=_token inside the form and they return the same value.

After that I backtracked to the method where the exception is thrown:


/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php


And echoed the test thats failing:

public function handle($request, Closure $next)
{
echo ($this->isReading($request) ? 'true' : 'false') . ' - ' . ($this->shouldPassThrough($request)? 'true' : 'false') . ' - ' . ($this->tokensMatch($request) ? 'true' : 'false');

if ($this->isReading($request) || $this->shouldPassThrough($request) || $this->tokensMatch($request)) {
return $this->addCookieToResponse($request, $next($request));
}

throw new TokenMismatchException;
}


And the result was:


false - false - false


I'm all out of ideas, HALP!

EXTRA:
I always clear the cookies before a test, I've changed all the permissions to read/write and I've added the meta name=csrf-token inside the head tag with the token.

EDIT:

Both

$request->input('_token')


And

$request->header('X-CSRF-TOKEN')


Inside handle() are null... how come?

SOLUTION:

Removed enctype="text/plain" from the form tag. That goes to show you: When a framework offers you idiot-proof renderers like Form::open(), JUST. USE. IT.

Answer

In your form (view) file. add these two lines. I hope it would work.

<form role="form" method="POST" action="{{ url('your action URL') }}">
<input type="hidden" name="_token" value="{{ session()->getToken() }}">