How To Get Human Readable File Size In PHP Laravel

Sometimes we need to check the uploaded file size in Laravel. Suppose you would like to check whether the uploaded file size is less than 2 MB or not? How you can check it? We know that when we upload a file in PHP Laravel then we don't see it in a human-readable format.

So I will show you with source code that laravel get file size in MB. Not only MB you will get automatically your uploaded file size in MB, KB even TB. I will create a simple custom method to get human-readable file size in Laravel. So you need to just follow this code.

Actually, we will show Laravel convert bytes to MB example with source code. Let's see the example of php laravel bytes to human-readable format:

 

Step 1: Download Laravel

I will show you the way of getting file size in MB in Laravel from scratch. So download a fresh Laravel project by this following command:

laravel new tutorial

//then 

cd tutorial

//then

php artisan serve

 

Step 2: Create Route

In this step, we need to route. One is for view form and the other is for submitting files to get file size in Laravel with human-readable.

routes/web.php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\FileController;

Route::get('/', [FileController::class,'index']);
Route::post('/', [FileController::class,'store'])->name('file');

 

Step 3: Create Controller

In this step, we have to implement the above two methods. One is for showing welcome page with form and other is for submitting form,

app\Http\Controllers\FileController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class FileController extends Controller
{
    public function index()
    {
        return view('welcome');
    }

    public function store(Request $request)
    {
        $size = $request->file('file')->getSize();

        return $this->convertUploadedFileToHumanReadable($size);
    }

    public function convertUploadedFileToHumanReadable($size, $precision = 2)
    {
        if ( $size > 0 ) {
            $size = (int) $size;
            $base = log($size) / log(1024);
            $suffixes = array(' bytes', ' KB', ' MB', ' GB', ' TB');
            return round(pow(1024, $base - floor($base)), $precision) . $suffixes[floor($base)];
        }

        return $size;
    }
}

 

Step 4: Create View

In this final step, we need to create a welcome.blade.php page. So let's create it and update it like below:

resources/views/welcome.blade.php

 

Now if you check, you will get the output like 1.95 KB after submitting the form.

 

Read also: Get File Size From Storage and Public Path in Laravel

 

Hope this getting file size in human-readable in Laravel tutorial will help you.

 

#laravel #laravel-8x