How to Convert Bytes into KB, MB and GB in PHP?

By Hardik Savani May 14, 2024 Category : PHP

Hi Developer,

In this example, I will show you how to convert bytes to kb mb gb in php. we will help you to give an example of how to convert bytes to kb in php. you will learn how to convert bytes to mb in php. This example will help you how to convert bytes to gb in php. Follow the below tutorial step of php convert bytes to mb.

In PHP, you can convert bytes into kilobytes (KB), megabytes (MB), and gigabytes (GB) by dividing the given number of bytes by the corresponding factor. Here's a simple example:

index.php

<?PHP

function formatBytes($bytes, $precision = 2) {

$kilobyte = 1024;

$megabyte = $kilobyte * 1024;

$gigabyte = $megabyte * 1024;

if ($bytes < $kilobyte) {

return $bytes . ' B';

} elseif ($bytes < $megabyte) {

return round($bytes / $kilobyte, $precision) . ' KB';

} elseif ($bytes < $gigabyte) {

return round($bytes / $megabyte, $precision) . ' MB';

} else {

return round($bytes / $gigabyte, $precision) . ' GB';

}

}

/* Example usage: */

$bytes = 567890123; /* Replace this with the actual number of bytes you have */

echo formatBytes($bytes);

?>

Output:

541.58 MB

This `formatBytes` function takes the number of bytes as input and converts it to the appropriate unit (B, KB, MB, GB) based on its magnitude. You can customize the precision parameter to control the number of decimal places in the result.

I hope it can help you...

Tags :
Shares