Home >Backend Development >PHP Tutorial >How to Convert Bytes to Kilobytes, Megabytes, and Gigabytes in PHP?

How to Convert Bytes to Kilobytes, Megabytes, and Gigabytes in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-19 13:17:03912browse

How to Convert Bytes to Kilobytes, Megabytes, and Gigabytes in PHP?

Formatting Byte Values: Convert Bytes to Kilobytes, Megabytes, and Gigabytes

When storing file sizes in a database, it's often recorded as bytes. However, for user readability, it's more practical to display these values in more manageable units such as kilobytes, megabytes, and gigabytes.

To achieve this, we can employ a PHP script like the one below:

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); 
   
    $bytes /= (1 << (10 * $pow));
   
    return round($bytes, $precision) . $units[$pow]; 
} 

This function takes the byte value as an argument and returns a formatted string that represents the size in the appropriate unit. For example, if you pass "5445632" bytes as input, the function will return "5.2 MB".

The above is the detailed content of How to Convert Bytes to Kilobytes, Megabytes, and Gigabytes in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn