Home > Backend Development > PHP Tutorial > How Do I Convert File Sizes from Bytes to Human-Readable Formats in PHP?

How Do I Convert File Sizes from Bytes to Human-Readable Formats in PHP?

Patricia Arquette
Release: 2024-11-27 01:24:10
Original
824 people have browsed it

How Do I Convert File Sizes from Bytes to Human-Readable Formats in PHP?

Computing File Sizes in Human-Readable Formats

Determining file sizes in meaningful units like kilobytes, megabytes, or gigabytes is a common task. When files are stored in bytes, a conversion is necessary for user-friendly display.

Solution

The PHP function formatBytes() offers a solution. Here's how it works:

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

Implementation

  1. Create an array $units containing the unit names (B, KB, MB, etc.).
  2. Calculate the power of 1024 to convert bytes to the appropriate unit.
  3. Divide $bytes by the calculated power to get the converted value.
  4. Round the result to the specified precision.
  5. Concatenate the formatted value with the corresponding unit name.

Example

To convert 5445632 bytes to a user-friendly format with two decimal places:

echo formatBytes(5445632, 2); // Output: 5.24 MB
Copy after login

The above is the detailed content of How Do I Convert File Sizes from Bytes to Human-Readable Formats 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