Computing File Sizes in Human-Readable Formats
Determining file sizes in meaningful units like kilobytes, megabytes, or gigabytes is a common task. When files are stored in bytes, a conversion is necessary for user-friendly display.
Solution
The PHP function formatBytes() offers a solution. Here's how it works:
function formatBytes($bytes, $precision = 2) { $units = array('B', 'KB', 'MB', 'GB', 'TB'); $bytes = max($bytes, 0); $pow = floor(($bytes ? log($bytes) : 0) / log(1024)); $pow = min($pow, count($units) - 1); // Uncomment one of the following alternatives // $bytes /= pow(1024, $pow); // $bytes /= (1 << (10 * $pow)); return round($bytes, $precision) . $units[$pow]; }
Implementation
Example
To convert 5445632 bytes to a user-friendly format with two decimal places:
echo formatBytes(5445632, 2); // Output: 5.24 MB
The above is the detailed content of How Do I Convert File Sizes from Bytes to Human-Readable Formats in PHP?. For more information, please follow other related articles on the PHP Chinese website!