"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Convert Bytes to Human-Readable File Sizes in PHP?

How to Convert Bytes to Human-Readable File Sizes in PHP?

Published on 2024-11-10
Browse:542

How to Convert Bytes to Human-Readable File Sizes in PHP?

How to ConvertBytes to Human-Readable File Sizes in Kilobytes, Megabytes, and Gigabytes

When working with file sizes stored in bytes, it's often necessary to display them in a more user-friendly format such as kilobytes, megabytes, and gigabytes. Here's a highly efficient PHP function that accomplishes this conversion precisely:

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 

For example, if you have a byte count of 5445632, using this function with formatBytes(5445632) will output "5.2 MB", displaying the size as megabytes with the specified precision of two decimal places.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3