Are there any specific PHP functions or libraries available to easily convert file sizes from bytes to KB or MB in PHP scripts?

To convert file sizes from bytes to KB or MB in PHP scripts, you can use the following approach: You can create a function that takes the file size in bytes as input and converts it to KB or MB based on the size. To convert bytes to KB, divide the size by 1024. To convert bytes to MB, divide the size by 1024*1024. Then, round the result to the desired decimal places for better readability.

function formatFileSize($size) {
    if ($size < 1024) {
        return $size . ' bytes';
    } elseif ($size < 1024*1024) {
        return round($size/1024, 2) . ' KB';
    } else {
        return round($size/(1024*1024), 2) . ' MB';
    }
}

// Example usage
$fileSizeInBytes = 2048;
echo formatFileSize($fileSizeInBytes); // Output: 2 KB