How to Get the File Size in PHP?

By Hardik Savani November 5, 2023 Category : PHP

Hi Artisan,

In this quick example, let's see how to get file size in php. you can understand a concept of get image size in php. This tutorial will give you a simple example of check image size in php. This article goes in detailed on get image size in bytes php.

Example 1:

In PHP, you can get the size of a file using the filesize() function. Here's an example code snippet:

Code:

<?php

$file = 'path/to/your/file.csv';

$fileSize = filesize($file);

echo "The size of the file is: " . $fileSize . " bytes";

?>

In this example, the filesize() function is used to get the size of the file at the specified path. The result is then stored in the $fileSize variable, and printed to the screen using the echo statement.

Example 2:

Note that the filesize() function returns the size of the file in bytes. If you want to display the size in a more human-readable format (such as kilobytes or megabytes), you can use some additional code to convert the result. Here's an example:

Code:

<?php

$fileSize = filesize($file);

$humanSize = round($fileSize / 1024 / 1024, 2) . ' MB';

echo "The size of the file is: " . $humanSize;

?>

In this example, the filesize() function is called as before, but the result is then divided by 1024 twice to convert it from bytes to megabytes. The round() function is used to round the result to two decimal places, and the result is then concatenated with the string 'MB' to create a human-readable file size.

I hope it can help you...

Tags :
Shares