PHP: How to convert numbers to bytes and vice versa

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

Overview

Understanding how to manipulate data sizes in PHP is essential for developers working with file uploads, memory limits, and more. This tutorial provides a deep dive into converting numbers to bytes and vice versa, with an array of code examples to guide you from simple to more complex scenarios.

Converting Numbers to Bytes

Converting an integer value that represents a specific data size into bytes is a fundamental task in many applications. We will start with the basics and gradually advance to incorporating these conversions into functional scripts.

Basic Integer to Bytes

To begin, let’s convert a number representing kilobytes (KB) to bytes:

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

echo kilobytesToBytes(1); // Outputs: 1024
?>

In this simple function, we multiply the given kilobytes by 1024 to find the equivalent number of bytes.

Advanced Conversions

Moving forward, we can define a comprehensive function that covers different units of data like MB, GB, and TB:

<?php
function convertToBytes($number, $unit) {
  $units = ['B' => 1, 'KB' => 1024, 'MB' => 1024**2, 'GB' => 1024**3, 'TB' => 1024**4];
  return $number * ($units[strtoupper($unit)] ?? 0);
}

echo convertToBytes(2, 'MB'); // Outputs: 2097152
?>

The function utilizes an associative array to map units to their byte values. We access the correct value by key and multiply.

Bytes to Numbers

Converting from bytes back to a unit of measurement is just as crucial and involves a bit more complex logic to account for different units.

Basic Bytes to Kilobytes

To convert bytes back to kilobytes, a simple function would look like this:

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

echo bytesToKilobytes(1024); // Outputs: 1
?>

We simply divide by 1024 to revert to kilobytes.

Dynamic Unit Conversion

For more complex conversions, such as dynamically determining to which unit to convert, consider the following function:

<?php
function bytesToUnit($bytes, $unit) {
  $units = ['B' => 1, 'KB' => 1024, 'MB' => 1024**2, 'GB' => 1024**3, 'TB' => 1024**4];
  return $bytes / ($units[strtoupper($unit)] ?? 1);
}

echo bytesToUnit(2097152, 'MB'); // Outputs: 2
?>

This function reverses the logic of the previous example, dividing bytes by the corresponding unit’s byte representation.

Working with File Sizes

One practical application of these conversions is handling file sizes. PHP’s filesize() function returns the file size in bytes.

Obtaining File Sizes

Here is how we can use the earlier bytesToUnit function to format the size of a file:

<?php
$file_path = 'example.jpg';
$file_size = filesize($file_path);

function formatFileSize($bytes, $unit = 'MB') {
  return bytesToUnit($bytes, $unit) . ' ' . $unit;
}

echo formatFileSize($file_size); // Outputs: 'Size in MB + MB'
?>

This script will output the size of ‘example.jpg’ in megabytes followed by the unit ‘MB’.

Human-Readable File Sizes

To make file sizes user-friendly, you can create a function that automatically selects the appropriate unit:

<?php
function humanReadableSize($bytes) {
  $units = ['B', 'KB', 'MB', 'GB', 'TB'];
  $factor = floor((strlen($bytes) - 1) / 3);
  return sprintf('%.2f', $bytes / pow(1024, $factor)) . ' ' . @$units[$factor];
}

echo humanReadableSize(2097152); // Outputs: '2.00 MB'
?>

This function dynamically calculates the factor based on the number of digits in the bytes value and adjusts the unit accordingly.

Conclusion

The ability to convert between numbers and bytes in PHP is pivotal for a variety of tasks, from handling uploads to displaying file sizes. By leveraging straightforward operations and creating versatile functions, you can easily handle the different data size conversions required by your applications. The code examples provided here will form a solid foundation for managing size conversions proficiently in PHP environments.