<?php
function convertFileSize($sizeInBytes, $unit = '')
{
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
$index = 0;
while ($sizeInBytes >= 1024 && $index < count($units) - 1) {
$sizeInBytes /= 1024;
$index++;
}
if ($unit && in_array($unit, $units)) {
return round($sizeInBytes, 2) . ' ' . $unit;
} else {
return round($sizeInBytes, 2) . ' ' . $units[$index];
}
}
// Example usage:
$fileSizeBytes = 1024 * 1024 * 5; // 5 MB
echo convertFileSize($fileSizeBytes) . "\n"; // Output: 5 MB
// Convert to a specific unit
echo convertFileSize($fileSizeBytes, 'KB') . "\n"; // Output: 5120 KB
?>