PHP: Convert bytes to KB, MB, GB and vice versa

Updated: January 9, 2024 By: Guest Contributor Post a comment

Introduction

When working with file sizes or system memory in PHP, it’s common to convert between different units of data storage. This tutorial will guide you through converting bytes to kilobytes, megabytes, and gigabytes and back, with examples ranging from simple to advanced.

Understanding Data Size Units

Before we delve into conversions, it’s important to understand the units of data commonly used in computing. The byte is the base unit, and multiples of bytes are usually represented in powers of 2, following the binary system. However, in terms of data storage, both binary (1 KB = 1024 bytes) and decimal (1 KB = 1000 bytes) prefixes are used. Here, we adhere to the binary system.

1 KB (Kilobyte) = 2^10 or 1024 bytes
1 MB (Megabyte) = 2^20 or 1,048,576 bytes
1 GB (Gigabyte) = 2^30 or 1,073,741,824 bytes

Basic Conversion Functions

The simplest way to perform conversions is through simple arithmetic operations. PHP, being a dynamic language, makes this process straightforward.

Bytes to Kilobytes

function bytesToKilobytes($bytes) {
    return $bytes / 1024;
}

Kilobytes to Bytes

function kilobytesToBytes($kilobytes) {
    return $kilobytes * 1024;
}

Bytes to Megabytes

function bytesToMegabytes($bytes) {
    return $bytes / 1048576;
}

Megabytes to Bytes

function megabytesToBytes($megabytes) {
    return $megabytes * 1048576;
}

Bytes to Gigabytes

function bytesToGigabytes($bytes) {
    return $bytes / 1073741824;
}

Gigabytes to Bytes

function gigabytesToBytes($gigabytes) {
    return $gigabytes * 1073741824;
}

Handling Large Numbers and Precision

When working with large file sizes, PHP functions like number_format() can be helpful to avoid precision problems and to format the result for readability.

Formatted Byte Conversion to MB

function formatBytesToMegabytes($bytes, $precision = 2) {
    $megabytes = bytesToMegabytes($bytes);
    return number_format($megabytes, $precision);
}

Advanced Conversion Techniques

For a more robust solution, especially when dealing with user-uploaded files or system information, it’s prudent to create a class that can handle conversions between any units dynamically.

Creating a SizeConverter Class

class SizeConverter {

    const UNITS = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB');

    public static function convert($size, $fromUnit, $toUnit, $precision = 2) {
        $fromIndex = array_search(strtoupper($fromUnit), self::UNITS);
        $toIndex = array_search(strtoupper($toUnit), self::UNITS);
        $unitDifference = $toIndex - $fromIndex;
        $unitFactor = pow(1024, $unitDifference);
        if ($unitDifference > 0) {
            return number_format($size / $unitFactor, $precision);
        } else {
            return number_format($size * $unitFactor, $precision);
        }
    }

}

With the SizeConverter class, you can now convert between any two units simply by calling the convert method and specifying the units and optionally, the desired precision.

Example of Using SizeConverter Class

$fileSizeInKilobytes = 256000;
$sizeInMB = SizeConverter::convert($fileSizeInKilobytes, 'KB', 'MB');
$sizeInGB = SizeConverter::convert($fileSizeInKilobytes, 'KB', 'GB', 3);

Dealing with User Input

Sometimes, user input determines the file sizes to convert. In such cases, implement validation to avoid unexpected results.

// Assuming $userInput is a string containing the size and unit, e.g., "2048 KB"
function convertUserInput($userInput) {
    preg_match('/(.*?)\s*([A-Z]+)/', strtoupper($userInput), $matches);
    if ($matches && count($matches) === 3) {
        $size = floatval($matches[1]);
        $unit = $matches[2];
        // Perform conversion using the SizeConverter class seen earlier
        return SizeConverter::convert($size, $unit, 'B');
    }
    return 'Invalid input';
}

Conclusion

In this tutorial, we explored how to convert bytes to different data size units in PHP and vice versa. We also looked at handling precision, user input, and creating a versatile conversion class. These methods can be integrated into your PHP applications to handle file sizes and memory usage efficiently.