mmstaniewski@gmail.com's avatar

Token mismatch when uploading some images, and it doesnt happen for the other photos

Hello,

I'm using Laravel 5 together with Intervention Image.

The thing that cause my headache is when i upload photos of one album, it normally goes through and uploads it, but when i want to add photos from another album "Token Mismatch Exception" happens. I can't understand whats going on here.

HTML Form: http://pastebin.com/ksJNrh3X and Controller method for this

  $image = Image::make($_FILES['cover']['tmp_name']);
  $name = sha1_file($_FILES['cover']['tmp_name']).'.jpg';
  $photo = Photo::create(['url' => $name, 'type' => 'albumcover']);
  $image->encode('jpg', 80)->save(public_path().'/uploads/gallery/covers/'.$name);
  $image->destroy();
  $album = Album::create(['title' => Input::get('albumTitle'), 'photo_id' => $photo->id]);

  foreach ($_FILES['photos']['name'] as $f => $name) {
  $image = Image::make($_FILES['photos']['tmp_name'][$f]);
  $name = sha1_file($_FILES['photos']['tmp_name'][$f]).'.jpg';


  $photo = Photo::create(['url' => $name, 'type' => 'gallery']);
  $image->encode('jpg', 80)->save(public_path().'/uploads/gallery/photos/'.$name);
  $image->destroy();
  AlbumPhoto::create(['album_id' => $album->id, 'photo_id' => $photo->id]);
}

The request is sent by normal POST, theres no AJAX used

0 likes
3 replies
oes's avatar

Have you included the CSRF token in your form for submission?

StuffedGoat's avatar

Could you replace this

<input name="_token" value="{ { csrf_token() } }" type="hidden" />

with this and give us an update?

{ { csrf_field() } }
afrayedknot's avatar

This is because your upload file is larger than your php.ini POST_MAX_SIZE.

So what happens is PHP clears your whole request - including the CSRF_TOKEN. When Laravel sees it, it is missing the _token - and therefore throws a TokenMismatchException.

There is middleware in 5.4 now to ValidatePostSize which detects this situation.

Make sure your POST_MAX_SIZE is sufficient large enough, so users are not caught out by this.

1 like

Please or to participate in this conversation.