What are the best practices for handling file size calculations in PHP applications?
When handling file size calculations in PHP applications, it's important to properly handle units of measurement (bytes, kilobytes, megabytes, etc.) to ensure accurate results. One common approach is to create a function that converts the file size to the desired unit before performing any calculations.
function formatFileSize($size, $unit = 'bytes') {
$units = array('bytes', 'KB', 'MB', 'GB', 'TB');
$index = array_search($unit, $units);
for ($i = 0; $size >= 1024 && $i < count($units); $i++) {
$size /= 1024;
}
return round($size, 2) . ' ' . $units[$i];
}
// Example usage
$fileSize = 1024 * 1024; // 1 MB
echo formatFileSize($fileSize, 'KB'); // Output: 1024 KB