PHP function to check file size in human-readable format
9. Human-Readable File Size
Write a PHP function that checks the file size and displays it in human-readable format (KB, MB, GB).
Sample Solution:
PHP Code :
<?php
function formatFileSize($filename) {
$size = filesize($filename);
$units = array('B', 'KB', 'MB', 'GB', 'TB');
$formattedSize = $size;
for ($i = 0; $size >= 1024 && $i < count($units) - 1; $i++) {
$size /= 1024;
$formattedSize = round($size, 2);
}
return $formattedSize . ' ' . $units[$i];
}
// Usage:
$filename = 'i:/test.txt';
$fileSize = formatFileSize($filename);
echo 'File size: ' . $fileSize;
?>
Sample Output:
File size: 533 B
Explanation:
In the above exercise -
- We define a function called formatFileSize() that takes a filename as input.
- Inside the function, we use the filesize() function to get the file size in bytes.
- We define an array called $units that holds the unit labels for the file size (B, KB, MB, GB, etc.). The loop iterates through the units to determine the appropriate unit based on the file size.
- We divide the file size by 1024 in each iteration of the loop until the size is less than 1024 or we reach the last unit. We also update the formatted size to the rounded divided size value.
- The function returns the formatted size appended to the appropriate unit.
Flowchart:

For more Practice: Solve these Related Problems:
- Write a PHP script to convert file sizes from bytes to KB, MB, or GB based on the file's size and display it.
- Write a PHP function to format file sizes, rounding to two decimal places, and include unit labels automatically.
- Write a PHP program to list all files in a directory along with their human-readable sizes, sorted by size.
- Write a PHP script to compare file sizes in different units by converting and formatting the results consistently.
PHP Code Editor:
Contribute your code and comments through Disqus.
Previous: PHP program to delete a file.
Next: Check if a file is writable or not.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.