In PHP, the function disk_total_space() is used to obtain the total disk space size for a specified path, returning the value in bytes. Usually, the number returned is very large and not easy to understand intuitively. Hence, we need to convert bytes into more comprehensible units, such as GB (gigabytes) or MB (megabytes).
This article will explain in detail how to convert the byte value returned by disk_total_space() into GB or MB, and clarify common unit conversion relationships.
The basic unit of computer storage capacity is the byte. The common unit conversions are as follows:
1 KB (Kilobyte) = 1024 Bytes
1 MB (Megabyte) = 1024 KB = 1024 × 1024 Bytes = 1,048,576 Bytes
1 GB (Gigabyte) = 1024 MB = 1024 × 1024 × 1024 Bytes = 1,073,741,824 Bytes
It is important to note that this uses binary conversion (base 1024), not decimal base 1000. Although some hard drive manufacturers use decimal conversion, computer systems usually calculate by 1024.
Below is a sample code demonstrating how to read total disk space in PHP and convert the byte value into GB and MB:
<?php
$path = '/'; // The path you want to check, modify as needed
// Get total disk space in bytes
$totalBytes = disk_total_space($path);
// Convert to GB, keeping two decimal places
$totalGB = $totalBytes / (1024 * 1024 * 1024);
$totalGBFormatted = number_format($totalGB, 2);
// Convert to MB, keeping two decimal places
$totalMB = $totalBytes / (1024 * 1024);
$totalMBFormatted = number_format($totalMB, 2);
echo "Total disk space: {$totalBytes} bytes
";
echo "Approximately: {$totalGBFormatted} GB
";
echo "Approximately: {$totalMBFormatted} MB
";
?>
In the code above:
disk_total_space() returns the byte count
Dividing by 1024 * 1024 * 1024 gives GB
Dividing by 1024 * 1024 gives MB
number_format formats the output, keeping two decimal places
Sometimes we don’t want to manually specify GB or MB. We can write a simple function that automatically selects the appropriate unit based on the size:
<?php
function formatBytes($bytes, $precision = 2) {
$units = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
$bytes /= pow(1024, $pow);
return round($bytes, $precision) . ' ' . $units[$pow];
}
$path = '/';
$totalBytes = disk_total_space($path);
echo "Total disk space is: " . formatBytes($totalBytes) . "
";
?>
This function determines the suitable unit by calculating the logarithm of the byte count, outputting a more user-friendly result.
disk_total_space() returns values in bytes
Convert bytes to MB by dividing by 1024 × 1024
Convert bytes to GB by dividing by 1024 × 1024 × 1024
Use formatting functions to make the results easier to read
Mastering the conversion between bytes and MB or GB helps you better understand disk space sizes, making it easier to display or judge space during development.