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
Release: 2024-11-19 13:17:03
Original
870 people have browsed it

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]; 
} 
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template