Laravel file does not exist - file upload - php

I am using a form to upload video files. For some reason all I get is the following error:
Symfony \ Component \ HttpFoundation \ File \ Exception \ FileNotFoundException
The file "" does not exist
In my controller I had a validation rule to require files, like so
$validator = Validator::make(Input::all(),
array(
'file' => 'required'
)
);
But because of the above rule, I couldn't properly debug what is going on, therefore I ended up removing it, as a result to generate the above error.

In the php.ini file, change the following:
upload_max_filesize = 20M
post_max_size = 20M
This should make it work.

Probably the problem is the "upload_max_filesize" that has been exceeded (check your php.ini), however it is a good practice to first check if the file is valid.
if (!$file->isValid()) {
throw new \Exception('Error on upload file: '.$file->getErrorMessage());
}
//...

In 2020 with Laravel 5.8, I discovered this problem and your answers gave me clues, but I was still getting an error when I tried the isValid method. I found this was the best way to check if a file was too large:
$file_result = new \stdClass();
if ($request->file('file_to_upload')->getSize() === false) {
$max_upload = min(ini_get('post_max_size'), ini_get('upload_max_filesize'));
//From: https://gist.github.com/svizion/2343619
$max_upload = str_replace('M', '', $max_upload);
$max_upload = $max_upload * 1024;
$file_result->error = "The file you are trying to upload is too large. The maximum size is " . $max_upload;
//return whatever json_encoded data your client-side app expects.
}
It looks as if the getSize method successfully returns false if the file size exceeds the maximum size. In my experience isValid throws an obscure error. The upload_max_filesize parameter is there to protect the server so I wanted a reliable way of catching when the user attempts to upload a large file and my client-side validation is not set correctly.

To clear the answer
The problem that you uploaded file which size is more than php configuration located in php.ini, so when you try to access the any property of the uploadFile object you will see the exception because file not exist

Related

Is it possible to force PHP code to continue running, if a php.ini directive such as upload_max_filesize is exceeded when uploaded file exceeds this?

I have a single PHP page, with the php (v7.4.7) script at the top of the page. The page functions as a file up-loader, allows up to 10 files per upload, and the max file size is set in the script.
The site works perfectly, generating a table of the result of each file to the user.
That is, unless someone uploads a file greater than the upload_max_filesize directive in the php.ini file. At which point, the script stops dead and cannot therefore, continue to provide the necessary results back to the user. No results are returned, the results table is therefore empty, and the user might think, wrongly, all went well.
I have tried adding try/catch blocks, but the script still fails to complete. Is this by design, or is there a way to coerce the script to run/complete, if this directive is exceeded? The HTML/PHP code is all pretty standard, as demonstrated by various tutorials etc.
Many thanks.
Violating upload_max_filesize doesn't abort the script execution. It'll just cause the error key in $_FILES to become UPLOAD_ERR_INI_SIZE.
Most likely, you're hitting an entirely different limit. For example, Apache has
LimitRequestBody and PHP itself has post_max_size or even max_file_uploads. In general, those directives don't abort the script either but simply wipe out the data excess.
My advice is to locate all the directives that may affect file uploads, set them one by one to an artificially low limit and verify what effect they have in your data. A check I typically do is to verify if $_SERVER['CONTENT_LENGTH'] is greater than zero for a request where $_SERVER['REQUEST_METHOD'] is POST but $_POST is empty. Aside that, checking error in $_FILES should have you fairly covered.
; Allow enough time for the upload to complete
max_input_time = 1200
; Max file size
upload_max_filesize = 50M
; Greater than upload_max_filesize to ease diagnose slightly large files
post_max_size = 100M
if (
empty($_FILES) &&
empty($_POST) &&
isset($_SERVER['REQUEST_METHOD']) &&
strtolower($_SERVER['REQUEST_METHOD'])=='post'
) {
// Error: post body was too large
// Bytes sent (and discarded): filter_input(INPUT_SERVER, 'CONTENT_LENGTH')
} elseif (
isset($_FILES['foo']) &&
$_FILES['foo']['error'] != UPLOAD_ERR_NO_FILE
){
// Upload
if ($_FILES['foo']['error'] === UPLOAD_ERR_OK) {
// Successful upload
}else{
// Failed upload
}
} else {
// No upload
}

Laravel 5.8 multi-upload inputs

I want to be able to upload multiple (dynamic) files (pdf).
So I have the following lay-out:
As you can see, the form has 4 input fields for files, but it also has 2 text fields and for every file upload row, it has a checkbox. The "flow" is the following:
Add title and year
Check the classes (Initiatie, Recreatie, Toersime, and Sport) you want to enable (and upload a PDF for)
Upload 1 PDF file per class.
The files are PDF files (1 per class). I tried the following code in PHP to upload the files, but I can only upload one, sometimes 2 files at a time, depending on how large the files are.
public function postGapersritAddResults(Request $request): RedirectResponse
{
// Handle upload
$path = 'documents/gapersrit/'.$request->get('year').'/results';
foreach (['initiatie', 'recreatie', 'toerisme', 'sport'] as $item) {
if ($request->hasFile('file_'.$item)) {
$request->file('file_'.$item)->storeAs($path, $item.'.'.$request->file('file_'.$item)->getClientOriginalExtension(), 'webdav');
}
}
// Handle database
$result = new SiteGapersritResults();
$result->title = $request->get('title');
$result->year = $request->get('year');
$result->initiatie = filter_var($request->get('active_initiatie'), FILTER_VALIDATE_BOOLEAN);
$result->recreatie = filter_var($request->get('active_recreatie'), FILTER_VALIDATE_BOOLEAN);
$result->toerisme = filter_var($request->get('active_toerisme'), FILTER_VALIDATE_BOOLEAN);
$result->sport = filter_var($request->get('active_sport'), FILTER_VALIDATE_BOOLEAN);
$result->save();
toastr()->success('Saved the results for year '.$result->year.'.', 'Success', ['timeOut' => 5000]);
return redirect()->to('admin/gapersrit/results');
}
If someone has a better idea of how I could do this, please help me out.
Ideally, I want to select all the files and be able to upload them one by one (like in my code), but for some reason, this doesn't work and throws most of the time the too large error, however, I guess I'm uploading one file at a time?
Edit
The limit for upload sizes is 100M in php.ini and my Nginx configuration.
Edit 2
I get the following error on my current code:
curl_exec(): CURLOPT_INFILE resource has gone away, resetting to default
full trace: https://pastebin.com/rqUeEhGa
This might be because the upload size is limited by the php.ini config of your server.
If you have access to the file or the php settings, try changing these values:
upload_max_filesize = 20M
post_max_size = 20M
Edit also see see https://stackoverflow.com/a/23686617/7584725
As you said, the error is curl_exec(): CURLOPT_INFILE resource has gone away, resetting to default
The code snippet you posted does not contain anything related to curl, the problem is the "webdav" disk in the saveAs function.
Looking at the trace, this seems like there is a problem in the League\Flysystem\WebDAV\ package, maybe
https://github.com/thephpleague/flysystem-webdav/issues/49 or
https://github.com/thephpleague/flysystem-webdav/issues/50

RuntimeException SplFileInfo::getSize(): stat failed for... Laravel 4 upload image

I work with laravel 4 (last update), I create a form where we could upload an image (logo/avatar). I am on MAC OS, I use sublime Text 3, laravel and MAMP Applications. All my configuration is setting right, no running problems.
My probleme is that I have this error when I submit the reaching fields from my form: RuntimeException
SplFileInfo::getSize(): stat failed for /Applications/MAMP/tmp/php/phpRUJfMX
Here's the code from my form nameOfTheForm.blade.php:
#extends('layout.default')
#section('title')
Name Of My Project - EditProfile
#stop
#section('content')
{{Form::open(array('url'=>'uploadAvatar','files' => true))}}
<p>
{{Form::label('pseudo','pseudo (*): ')}}
{{Form::text('pseudo',Input::old('nom'))}}
</p>
#if ($errors->has('pseudo'))
<p class='error'> {{ $errors->first('pseudo')}}</p>
#endif
<br>
<br>
<p>
{{Form::label('url_Avatar','Avatar: ')}}
{{Form::file('url_Avatar',Input::old('Url_Avatar'))}}
</p>
#if ($errors->has('url_Avatar'))
<p class='error'> {{ $errors->first('url_Avatar')}}</p>
#endif
<br>
<br>
<p>
{{Form::submit('Validate your avatar')}}
</p>
{{Form::close()}}
#stop
Here's the code from my controller:
public function uploadAvatar() {
//*****UPLOAD FILE (on server it's an image, on the DB it's an url*****
$file = Input::File('url_Avatar');
//set a register path to the uploaded file
$destinationPath = public_path().'/upload/';
//have client extension loaded file and set a random name to the uploaded file, produce a random string of length 32 made up of alphanumeric characters [a-zA-z0-9]
$filename = $destinationPath . '' . str_random(32) . '.' . $file->getClientOriginalExtension();
$uploaded = Input::File('url_Avatar')->move($destinationPath,$filename);
//*****VALIDATORS INPUTS and RULES*****
$inputs = Input::all();
$rules = array(
'pseudo' => 'required|between:1,64|unique:profile,pseudo',
//urlAvatar is an url in database but we register as an image on the server
'url_Avatar' => 'required|image|min:1',
);
The uploaded file code works perfect, I register the file in the selected folder I want. I Have no problem with my routes (no need to show this part of the code).
But When I submit the form, I have this error:
RuntimeException
SplFileInfo::getSize(): stat failed for /Applications/MAMP/tmp/php/phpRUJfMX
error info details:
open:/Applications/MAMP/htdocs/nameOfMyProject/vendor/laravel/framework/src/Illuminate/Validation/Validator.php
}
elseif (is_array($value))
{
return count($value);
}
elseif ($value instanceof File)
{
return $value->getSize() / 1024;
}
else
It seems, that Laravel needs (stat - Gives information about a file), that is to say, needs to have the informations from the uploaded file, here the size, but I try this in my controller just before the line where here's $uploaded where I move the file in my selected folder:
//I add this line code before
$size= $file->getSize();
$uploaded=Input::File('url_Avatar')->move($destinationPath,$filename);
But, when I did that, I have another error: the validator doesn't r**ecognize the files as an image** et ask me to upload a valid format. I think I need to correct the first errors I had (SplFileInfo::getSize())
If you have any ideas... Thank you.
Short version: Laravel's Symphony source returns file size of 0 if the file size is larger than php.ini's upload_max_filesize.
Recommend checking your php.ini file. I'm not sure how MAMP handles php.ini but it's there if you're running Laravel. In php.ini, the upload_max_filesize may be smaller than the file you're attempting to upload. That value happened to be defaulted on my Ubuntu 12.10 VM to 2megs.
Check
/vendor/symphony/http-foundation/Symphony/Component/HttpFoundation/File/UploadedFile.php
and check the getMaxFilesize(). By default, this method grabs the upload_max_filesize value from your PHP.ini file on your host system.
The interesting thing about this is that if you do
$foo = Input::file('uploaded_file')
var_dump($foo)
or
use Laravel's die&dump dd($foo), then a file that's larger than php.ini's upload_max_filesize returns a size of 0.
In addition to upload_max_filesize, PHP docs also mention checking php.ini so that:
- post_max_size must be larger than upload_max_filesize
- memory_limit should be larger than post_max_size
I got same error In Laravel 6x. This error is due to null value for column which was not nullable.
To resolve I just changed column to accept null after that is working fine.
I know this question has been answered quite some time ago, but I found something on the PHP website which might be useful because it actually explains why the error occurs:
If you're using Symfony's UploadedFile,
please be aware that if you call this method
after you call #move, you will most likely get
some obscenely untraceable error, that says:
stat failed
Which if you really think about it, it does makes sense,
the file has been moved by Symfony, but getSize is in SplFileInfo,
and SplFileInfo doesn't know that the file has been moved.
Source: https://www.php.net/manual/en/splfileinfo.getsize.php#122780
i solve my problem with edit columns attribute default "null" and the problem gone.

$_FILES field 'tmp_name' has no value on .JPG file extension

i was making an upload script when i tested an image file wit this extension .JPG, i don't know whats the difference between jpg or jpeg, but it seems that $_FILES don't recognize this file type.
I've read several threads that $_FILES ins't that reliable when it comes to mime type, so i decided to used the php's mime type function mime_content_type(), php's getimagesize(), pathinfo(), though pathinfo returns a file name, and type, but i need the path of the file which is NOT present, all of the functions are being passed with $_FILES['file']['tmp_name'] as parameters.
So this problem came up when i decided to upload an image file e.g sample.JPG, i think most of this files are raw from the camera <-- that's what i think though but nevertheless what is more important is that i can upload them .JPG, .jpg, jpeg, .png. all of them works fine except for .JPG.
Main problem is that field ['tmp_name'] in $_FILES has no values when .JPG is to be uploaded.
Any of you guys who have encountered this problem please do share your workaround or "how did you do it" kind of thing.
If $_FILES[$field]['tmp_name'] is empty then the file hasn't been uploaded. You should look at $_FILES[$field]['error'] to see why.
FWIW, and as far as I understand it, the mime-type in $_FILES[] is provided by the browser.
Update: here is a bit of potted code to handle all file upload errors:
$message = 'Error uploading file';
switch( $_FILES['newfile']['error'] ) {
case UPLOAD_ERR_OK:
$message = false;;
break;
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
$message .= ' - file too large (limit of '.get_max_upload().' bytes).';
break;
case UPLOAD_ERR_PARTIAL:
$message .= ' - file upload was not completed.';
break;
case UPLOAD_ERR_NO_FILE:
$message .= ' - zero-length file uploaded.';
break;
default:
$message .= ' - internal error #'.$_FILES['newfile']['error'];
break;
}
if( !$message ) {
if( !is_uploaded_file($_FILES['newfile']['tmp_name']) ) {
$message = 'Error uploading file - unknown error.';
} else {
// Let's see if we can move the file...
$dest .= '/'.$this_file;
if( !move_uploaded_file($_FILES['newfile']['tmp_name'], $dest) ) { // No error supporession so we can see the underlying error.
$message = 'Error uploading file - could not save upload (this will probably be a permissions problem in '.$dest.')';
} else {
$message = 'File uploaded okay.';
}
}
}
Check your php.ini and in particular this setting
; Maximum allowed size for uploaded files.
; http://www.php.net/manual/en/ini.core.php#ini.upload-max-filesize
upload_max_filesize = 6M
Or do this in your Apache Config:
<Directory "/var/www/vhosts/path/to/your/directory/import/">
php_value post_max_size 6M
php_value upload_max_filesize 6M
</Directory>
I would also say that it is poor that PHP doesn't report an error in the error logs if you upload a file that is larger than your php.ini upload_max_filesize setting. For example, if you upload a 6MB file when you have it set at 2M (which I think is the default).
Posting an answer because my rating is too low.
Remember to restart your server after setting the max file size cap in your php.ini. I spent hours on this issue thinking that it wasn't a file size problem meanwhile I forgot to restart. After restart everything worked.
I hope this can help someone.
I was having the same problem and being familiar with mostly .NET platform makes you forget about stuff that happens in the client side html.
My problem was my form is having a MAX_FILE_SIZE hidden input which has some value lesser than file's equavalent bytes.
Your form should have this;
Other than that, your form tag must include enctype="multipart/form-data"
I was thining that max file size was in kb, but it's in bytes, thanks to some other page in stackoverflow.
The other reason that might cause this problem your php.ini settings that people have mentioned in previous comments. You should can post_max_size = 200M to php.ini file too.
If you are developing on Windows like me, you can see a dump file that showing errors at C:\Windows\Temp called as "php**VERSION**_errors.log". It helps.
Seems as though it's a random problem because while I was making a script to upload CSV files, some CSV files would have no problem uploading but in other cases, $_FILES['file'][tmp_name] would be empty.
I faced the issue with $_FILES field 'tmp_name' having no value for .JPG file extension and successfully fixed it in few steps. These measures may help someone in the future.
First of all, I implemented the Switch Case solution offered by the
user 'staticsan'. Link here -
https://stackoverflow.com/a/14472801/3681985. This solution helped me
trace the potential issues such as parameters in php.ini file and
folder permissions.
The php.ini file was named php.ini.default. Changing the parameters upload_max_filesize and post_max_size didn't yield any result, until I renamed the file to php.ini. Remember to experiment with parameter values.
After fixing the file name issue, I encountered a challenge with the permissions to the folder in which the uploaded temp image has to be moved. I have changed the permissions and was able to see the image uploaded in to the folder.
Just try this and see what happens,
if (($_FILES['file']['type']) == "image/jpg" || ($_FILES['file']['type']) == "image/jpeg") {
//do uploading stuff here
}else{
echo 'File is not a valid JPG,JPEG';
}

File upload results in file size 0 and error code 0

I'm trying to upload an image to a php script. I have a, non-persistent, bug that results in some of the images uploaded has a file size of 0. I have tried to print the _FILES array to my log file, and it shows the error code being 0, which should be ok.
These lines:
foreach($_FILES['image_file'] as $key => $val){
error_log(date('j/n/o H:i:s')." ". $key ." => ".$val. "\n", 3,$log_path);
}
Give me these in the log file:
3/10/2012 12:12:54 name => 59175248636.jpg
3/10/2012 12:12:54 type => image/jpeg
3/10/2012 12:12:54 tmp_name => C:\WINDOWS\Temp\php411F.tmp
3/10/2012 12:12:54 error => 0
3/10/2012 12:12:54 size => 0
As can be read from the log file, this script runs on a Windows machine, of which I have limited knowledge. I have already changed the post_max_size to 10M, as well as upload_max_size to 10M in the php.ini.
I am flabbergasted about this issue. When I test from my own devices, it works fine, but for some reason, when my testers try it out, it fails.
EDIT - Try this:
I think you may need to change $_FILES['file'] to $_FILES['image_file'] to work with your setup. I have left it as below for ease of reading...
if ($_FILES['file']['error'] === UPLOAD_ERR_OK && $_FILES['file']['size'] > 0){
... upload was successful ...
}elseif($_FILES['file']['error'] === UPLOAD_ERR_OK && $_FILES['file']['size'] == 0){
die("Upload failed, random upload issue... please try again);
// change this error to something more useful... (leave this error in for testing)
}else {
die("Upload failed with error code " . $_FILES['file']['error']);
}
This doesn't solve the random filesize issue, but it will allow your code / process to continue. Treat it as a failed upload and tell the user to try again...
Used code from this stackoverflow post posted by Marc B
Since I run into this from time to time, I guess I'll just post one reason this could happen: Size and error 0 can occur if you try drag and dropping a file from a Windows Explorer view of a zipped file (double click a zipped file and it opens up just like a folder) to your uploader. I use DropzoneJS a lot and by default, it processes these files immediately and pushes it to my server, which ends up seeing a 0 bytes file with no file upload errors. So if your users are doing the above, that could be the reason why you end up with such files.

Categories