TokenMismatchException in VerifyCsrfToken.php line 67 when uploading video - php

Picture 2 Form
Picture 3 Form
Hi,
I'm getting the error mentioned in the title when trying to upload a video using Laravel 5.2.
Images work correctly.
I've checked the PHP.ini settings of my MAMP server.
I'm using the form facade so I don't have to import token into my form.
I'm clueless, does anybody have suggestions what it might be?
<div class="container spark-screen">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-heading">Bestand uploaden</div>
<div class="panel-body">
{!! Form::open(
array(
'url' => 'uploads',
'class' => 'form',
'novalidate' => 'novalidate',
'files' => true)) !!}
#include('uploadspanel.create_form')
{!! Form::close() !!}
</div>
</div>
</div>
</div>
</div>
controller:
public function store(UploadRequest $request){
$extension = Input::file('file')->getClientOriginalExtension();
$filename = rand(11111111, 99999999). '.' . $extension;
Input::file('file')->move(
base_path().'/public/files/uploads/', $filename
);
$approved = $request['approved'];
$fullPath = '/public/files/uploads/' . $filename;
$upload = new Uploads(array(
'name' => $request['name'],
'format' => $extension,
'path' => $fullPath,
'approved' => $approved,
));
$upload->save();
$uploads = Uploads::orderBy('approved')->get();
return view('uploadspanel.index', compact('uploads'));
}

Make sure you have the token included in your form, go to your page and inspect it, you should see something like this:
<input name="_token" type="hidden" value="Th4yqxNa3w3ooVAxRcSgvMug7ZEPA6BtaUw4qRck">
if you don't then add it in your blade like this:
{{ Form::hidden("_token", csrf_token()) }}
Another issue you might have is in case you are submitting this form through an AJAX request, in that case, you would need to pass the token there too:
$.ajax({
url : '{{ route("your_route", optional_parameter) }}',
type : "post",
data : { '_token' : '{{ csrf_token() }}', 'var1' : var1 },
}).done(...)

It had to do with MAMP settings. figured it out when i echo php_info();
then on line 6 or 7 followed the path to my php.ini
then changed the inputs again with another editor, saved it.
retart MAMP server
and done

This happens when your file which you are uploading is smaller than the max upload size but more than the POST_MAX_SIZE.
The input is truncated at the POST_MAX_SIZE which means that the csrf token is lost.
You can change these values in php.ini file.

Related

How can get the name of a image stored in /storage/public if was dynamic name

My problem is that i upload a image on the website in laravel but the database save the path of my local storage with a strange name and extension:
The picture was uploaded fine in Storage/app/public but with another name (Like a hash code):
Now, how can get this name in /Storage/Public with a query on a database, or how can upload the image with the original name or by ID?
Code:
Form upload:
<form class="formulario" method="POST" enctype='multipart/form-data' action="{{ route('add_taller') }}">
#csrf
<h4>Añade el titulo correspondiente</h4><input name="titulo">
<h4>Añade un logo al taller</h4><input type="file" name="icono" class="taller_form {{ $errors->has('name') ? 'alert alert-danger' : ''}}" />
{!! $errors->first('image', '<p class="alerta">:message</p>') !!}
<h4>Añade una descripción</h4><textarea name="descripcion" rows="10" cols="50" value="{{ old('textarea') }}"></textarea>
{!! $errors->first('string', '<p class="alerta">:message</p>') !!}
<button type="submit">Subir a la web</button>
</form>
In controller:
public function add_taller(Request $request)
{
$request->file('icono')->store('public');
$user = Auth::user();
DB::table('talleres')->insert([
'icono' =>$request->icono,
'titulo' => $request->titulo,
'descripcion' => $request->descripcion,
'user_id' => $user->id,
'fecha'=> now()]);
return view('home');
}
View where I need to show the picture:
#foreach($datos as $dato)
<div class="taller">
<div>
<img src="{{Storage::url($dato->icono)}}" alt="" srcset="" class="icon_taller">
</div>
<div>
<h4>{{$dato->titulo}}</h4>
<p>{{$dato->descripcion}}</p>
</div>
<div class="botones_area">
<button>Descarga</button>
<button>Contacto</button>
</div>
</div>
#endforeach
As I can see, you don't save the path with the file extension.
When you use $request->file('icono')->store('public'); you generate a temporal file and the file extension is determined by Laravel with the MIME type.
What's about:
public function add_taller(Request $request)
{
$path = Storage::putFileAs(
'public', $request->file('icono'), Str::uuid()
);
$user = Auth::user();
DB::table('talleres')->insert([
'icono' => $path,
'titulo' => $request->titulo,
'descripcion' => $request->description,
'user_id' => $user->id,
'fecha'=> now()]
);
return view('home');
}
For the filename, I've used Str::uuid function to generate names with a different id. For store files, I've used Storage Laravel facade, take a quick look here: https://laravel.com/docs/8.x/filesystem#specifying-a-file-name
What do you think about these changes?

php settings on local vs production server (laravel)

I have made a laravel project where users can upload images. I have tested the project on local server and found nothing wrong. After uploading the project to the production server I found that, when a user tries to upload images that are greater than 1.5mb size, it shows error TokenMismatchException in VerifyCsrfToken.php line 67 although i have
csrf token in my form. After couple of searching I found that some people are suggesting to change the two things in php.ini file and restart the nginx server. So I have changed the post_max_size = 40M upload_max_filesize = 40M and also changed the max_execution_time = 0 which means unlimited execution time. Then I run this command sudo service nginx restart and php artisan up and tried to upload an image which is 21MB size. When I pressed the submit button, It took sometime to upload the image and eventually threw the token mismatch exception. I am using ubuntu 16.04 for local tests. Any solution to this problem please?
I am sharing the codes:
view:
{!! Form::open(['url'=> "pro/{$user->id}/upload",'files'=> 'true', 'class'=> 'form-horizontal']) !!}
<input id="filebutton" name="image" class="input-file" type="file">
<input name="title" class="form-control" type="text" required="">
<button type="submit" class="btn btn-danger btn-block btn-flat">Upload</button>
{!! Form::close() !!}
controller:
public function save($id, PortfolioRequest $request)
{
$pro = User::findOrFail($id);
$file = $request->file('image');
$original_path = public_path('uploads/portfolio/original/');
$file_name = str_random(64).'_'.$request->title.'_user_'. $pro->id . '.' . $file->getClientOriginalExtension();
Image::make($file)
->resize(750,null,function ($constraint) {
$constraint->aspectRatio();
})
->save($original_path . $file_name);
$portfolio = Portfolio::create([
'user_id' => $id,
'image' => $file_name,
'title' => $request->title
]);
return redirect("pro/{$id}/portfolio");
}
the generated form:
<form method="POST" action="www.xxxx.com/pro/3/upload" accept-charset="UTF-8" class="form-horizontal" enctype="multipart/form-data"><input name="_token" type="hidden" value="EsH8KaSSoXovzjZ0RnWWi7eEwNWNgYlBVRm7yUYr">
Try adding this to your <header>:
<meta name="csrf-token" content="{{ csrf_token() }}" />

Input file in laravel 5.2?

I'm trying to upload a file, but it fails when the request lands to the controller.
With fails i mean that if i try $request->hasFile("filename") always returns false.
Is there some specific field that I have to specify in the view?
This is a snippet of the view:
<body>
<form action="{{url('dev/tester')}}" method="POST">
{{csrf_field()}}
<input type="file" name="file">
<button type="submit">Test</button>
</form>
</body>
And here is the controller
class Tester extends Controller
{
public function index(Request $request)
{
if($request->hasFile('file'))
{
dd('Got the file');
}
dd('No file');
}
public function testView()
{
return view('tests.file_upload');
}
}
I always get returned 'No file'.
Any clue? I've even check the php.ini to see if there was a size limitation but it's all set to 32M as MAMP's pro default settings...
Check if you may have forgotten to add enctype="multipart/form-data" in form
You must enabling upload form to your form,
there is 2 ways to do it :
By using HTML
<form action="{{url('dev/tester')}}" method="post" enctype="multipart/form-data">
By using laravel Form & HTML (https://laravelcollective.com/docs/5.2/html)
{!! Form::open( [ 'action' => url( 'dev/tester' ), 'method' => 'post', 'files' => true ] ) !!}
// Your form
{!! Form::close() !!}
This should work like a charm!
Try adding the enctype="multipart/from-data" to your form, then it should work!

Upload pdf file using Laravel 5

I'm using Laravel 5.2 and I want to make a form which can upload a pdf file with it. I want to add that file on folder "files" in "public" folder. here is my view:
<div class="form-group">
<label for="upload_file" class="control-label col-sm-3">Upload File</label>
<div class="col-sm-9">
<input class="form-control" type="file" name="upload_file" id="upload_file">
</div>
</div>
and what should I do next? what should I add in my controller and route?
First you should add enctype="multipart/form-data" to your <form> tag. Then in your controller handle the file upload as follow:
class FileController extends Controller
{
// ...
public function upload(Request $request)
{
$uniqueFileName = uniqid() . $request->get('upload_file')->getClientOriginalName() . '.' . $request->get('upload_file')->getClientOriginalExtension());
$request->get('upload_file')->move(public_path('files') . $uniqueFileName);
return redirect()->back()->with('success', 'File uploaded successfully.');
}
// ...
}
Link to Laravel Docs for Handling File Uploads
Laravel casts the file type params in request to UploadedFile objects. You can see Symfony's UploadedFile class here for available methods and attributes.
First of all, the documentation tells you exactly what to do here.
What you want to do is adding this to your <form> tag:
enctype="multipart/form-data" (This allows you to upload data), set a method(get/post) and an action (url).
Then you want to set up your routes.
For example:
Route::post('/pdf/upload', 'FileController#upload');
This way you make sure that when you send the form it will go to your FileController with upload as function.
In your controller you want to declare the file as explained in the docs.
$file = $request->file('photo');.
From this point you can do whatever you'd like to do with the file ($file). For example uploading it to your own server.
public function store(Request $request)
{
if($request->file('file'))
{
$file = $request->file('file');
$filename = time() . '.' . $request->file('file')->extension();
$filePath = public_path() . '/files/uploads/';
$file->move($filePath, $filename);
}
}
You Could Use Simple Method It Can Save The File
$path = $request->file('avatar')->store('avatars');
For More Information Here
you can this code for upload file in Laravel:
$request->file('upload_file')->move($path,$name);
You can take a look at how i upload files, all files are accepted:
first the code for the create.blade.php form
{!! Form::open(
array(
'url' => 'uploads',
'method' => 'post',
'class' => 'form',
'novalidate' => 'novalidate',
'files' => true)) !!}
#include('uploadspanel.create_form')
{!! Form::close() !!}
Remember to set files to true
Then the uploadspanel.create_form
<div class="form-group">
{!! Form::label('name', 'Name:') !!}
{!! Form::text('name', null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('file', 'Bestand:') !!}
{!! Form::file('file',null,['class'=>'form-control']) !!}
</div>
#if(\Auth::user()->level == 2)
<div class="form-group">
{{ Form::label('approved', 'Beschikbaar voor:') }}
{{ Form::select('approved', array(1 => 'Iedereen', 2 => 'monteurs', 3 => 'concept'), null, ['class' => 'form-control']) }}
</div>
#else
{{ Form::hidden('approved', 3) }}
#endif
<div class="form-group">
{!! Form::submit('Bestanden uploaden',['class' => 'btn btn-primary form-control']) !!}
</div>
then the controller store function
public function store(UploadRequest $request){
$extension = Input::file('file')->getClientOriginalExtension();
$filename = rand(11111111, 99999999). '.' . $extension;
Input::file('file')->move(
base_path().'/public/files/uploads/', $filename
);
if(\Auth::user()->level == 2) {
$approved = $request['approved'];
} else {
$approved = 3;
}
$fullPath = '/public/files/uploads/' . $filename;
$upload = new Uploads(array(
'name' => $request['name'],
'format' => $extension,
'path' => $fullPath,
'approved' => $approved,
));
$upload->save();
$uploads = Uploads::orderBy('approved')->get();
return view('uploadspanel.index', compact('uploads'));
}

Laravel 4 upload image form

I'm trying to make a form that allows uploading a file and store it in the public/upload folder of the application.
my form is:
<form action="/image/save" method="post">
<input name="image" type="file" />
<input type="submit" value="Save"/>
</form>
and the controller:
public function save(){
$file = Input::file('image');
$destinationPath = 'upload/';
$filename = $file->getClientOriginalName();
Input::file('image')->move($destinationPath, $filename);
But when I run it I get the following error:
Call to a member function getClientOriginalName() on a non-object
You need to have a file input enabled on a form. (Doc)
In Laravel, you can use:
Form::open('image/save', array('files'=> true))
or
<form action="/images/save" method="post" enctype="multipart/form-data">
Otherwise all you are receiving from the file input is the file name as a string.
If you not use Blade for generate your form like this
{{ Form::open(array('url' => 'foo/bar', 'files' => true)) }}
Just add this parameter to your form tag
enctype="multipart/form-data"
I also faced the same problem with one of my forms, the problem was the form wasn't defined with the option, 'files' => true , which tells the Laravel4 form helper to define a form with enctype="multipart/form-data"
Here is what i did:
Define the following array in your controller and pass it to your view ,
$form_options = array (
'url' => 'path/to/defined/route',
'class' => 'form-horizontal',
'name' => 'newUser',
'files' => true
);
In your view, define your form as follows:
{{ Form::open( $form_options ) }}
That will define your form with enctype="multipart/form-data"
You have to get the filename as follows:
//Blade form
{{ Form::open_for_files('/image/save') }}
{{ Form::file('image') }}
{{ Form::close() }}
//get imagename
$filename = Input::file('image.name');
Good luck! :)
You can just add the field 'files'=> true in your array() if you use Laravel form style something like
{{ Form::open(array('url'=>'/images/save','role'=>'form','files'=> true)) }}
otherwise you can use the html form tag something like
<form action="/images/save" method="post" enctype="multipart/form-data">
Hope this will help you.

Categories