How to Validate on Max File Size in Laravel?
According to the documentation:
$validator = Validator::make($request->all(), [
'file' => 'max:500000',
]);
The value is in kilobytes. I.e. max:10240
= max 10 MB.
Laravel file size validation returns error regardless of file size
size:value => The field under validation must have a size matching the given value.
Use max
instead of size
$validatedData = $request->validate(['profilePhoto' => 'required|image|max:256']);
Note that the value is in kilobytes. I.e. max:10240 = max 10 MB.
Laravel - validate file size when PHP max upload size limit is exceeded
You don't seem interested in changing the PHP limits to allow larger files. It looks to me like you want your max upload to be 5MB, and return a proper response if it is over that.
You can handle the FileException
exception inside your exception handler at app/Exceptions/Handler.php
. Update the render
method to add in the code you need. For example, if you'd like to return a validation exception, you will need to handle the validation inside the exception handler for the FileException
exception.
public function render($request, Exception $exception)
{
if ($exception instanceof \Symfony\Component\HttpFoundation\File\Exception\FileException) {
// create a validator and validate to throw a new ValidationException
return Validator::make($request->all(), [
'your_file_input' => 'required|file|size:5000',
])->validate();
}
return parent::render($request, $exception);
}
This is untested, but should give you the general idea.
You can also do client side validation via javascript, so that a file that is too large is never actually sent to your server, but javascript can be disabled or removed by the client, so it would be good to have nice server side handling set up.
For the client side validation, if you attach an event handler to the "change" event for the file input, you can check the file size using this.files[0].size
, and perform any additional actions after that (disable form, remove uploaded file, etc.)
Laravel: How to validate multiple size rules on same file based on mime-type
you can validate based on file mime type like below psudo-code:
public function upload(Request $request) {
$rules = [];
$image_max_size = 1024 * 2;
$video_max_size = 1024 * 500;
foreach($request->file('file') as $index => $file){
if(in_array($file->getMimeType(), ['image/jpg', 'image/jpeg', 'image/png']) {
$rules["file.$index"] = ["max:$image_max_size"];
} else if (in_array($file->getMimeType(), ['video/mp4']){
$rules["file.$index"] = ["max:$video_max_size"];
} else {
// Always non-validating => returns error
$rules["file.$index"] = ['bail', 'mimes:jpg,jpeg,png,mp4'];
}
}
$request->validate($rules);
...
}
I had similar problem and make that solved using this approach.
Validate max number of multiple files that can be attached in Laravel Validation
As attachments
is an array, you can use max
rule to validate it max elements as 3
$messages = [
"attachments.max" => "file can't be more than 3."
];
$this->validate($request, [
'attachments.*' => 'mimes:jpg,jpeg,bmp,png|max:5000',
'attachments' => 'max:3',
],$messages);
How to change Laravel Validation message for max file size in MB instead of KB?
You can extend the validator to add your own rule and use the same logic without the conversion to kb. You can add a call to Validator::extend
to your AppServiceProvider.
<?php namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Validator::extend('max_mb', function($attribute, $value, $parameters, $validator) {
$this->requireParameterCount(1, $parameters, 'max_mb');
if ($value instanceof UploadedFile && ! $value->isValid()) {
return false;
}
// If call getSize()/1024/1024 on $value here it'll be numeric and not
// get divided by 1024 once in the Validator::getSize() method.
$megabytes = $value->getSize() / 1024 / 1024;
return $this->getSize($attribute, $megabytes) <= $parameters[0];
});
}
}
Then to add the error message you can just add it to your validation lang file.
See the section on custom validation rules in the manual
Laravel max validation doesn't take effect on file upload and I can still upload images that are bigger than the limit. Why is this happening?
$this->validate($request, [
'files' => 'required',
'files.*' => 'required|max:4096',
]);
How to Validate File Upload in Laravel
in laravel you can not handle this case in controller as it will not get to controller/customrequest and will be handled in middleware so you can handle this in ValidatePostSize.php file:
public function handle($request, Closure $next)
{
// if ($request->server('CONTENT_LENGTH') > $this->getPostMaxSize())
{
// throw new PostTooLargeException;
// }
return $next($request);
}
/**
* Determine the server 'post_max_size' as bytes.
*
* @return int
*/
protected function getPostMaxSize()
{
if (is_numeric($postMaxSize = ini_get('post_max_size'))) {
return (int) $postMaxSize;
}
$metric = strtoupper(substr($postMaxSize, -1));
switch ($metric) {
case 'K':
return (int) $postMaxSize * 1024;
case 'M':
return (int) $postMaxSize * 1048576;
default:
return (int) $postMaxSize;
}
}
with your custom message
Or in App\Exceptions\Handler:
public function render($request, Exception $exception)
{
if ($exception instanceof \Illuminate\Http\Exceptions\PostTooLargeException) {
// handle response accordingly
}
return parent::render($request, $exception);
}
Else need to update php.ini
upload_max_filesize = 10MB
If you dont to work with any of above solutions you can use client side validation like if you are using jQuery e.g.:
$(document).on("change", "#elementId", function(e) {
if(this.files[0].size > 7244183) //set required file size 2048 ( 2MB )
{
alert("The file size is too larage");
$('#elemendId').value = "";
}
});
or
<script type="text/javascript">
function ValidateSize(file) {
var FileSize = file.files[0].size / 1024 / 1024; // in MB
if (FileSize > 2) {
alert('File size exceeds 2 MB');
$(file).val(''); //for clearing with Jquery
} else {
}
}
</script>
Related Topics
PHP Error: "The Zip Extension and Unzip Command Are Both Missing, Skipping."
Securing a Rest API Accessible from Android
Using Comparison Operators in a PHP 'Switch' Statement
Checking for Empty Arrays: Count VS Empty
How to Use JSON.Stringify and JSON_Decode() Properly
Printing to Pos Printer from PHP
In Laravel How to Add Values to a Request Array
Learning Select from Where Prepared Statements
How to Upload an Image as Attachment with Slack API
Lsa - Latent Semantic Analysis - How to Code It in PHP