PHP: disk_free_space() formatting
Back to PHP.
I tried using system() to get the remaining disk space on my server using
df. But it was challenging to debug it under a PHP-FPM chroot (the PHP
scripts literally see /whatever/chroot/directory as the root directory /
and cannot see anything "up" from there.)
Turns out, PHP already has that covered (of course it does!) with a built-in function.
The output of disk_free_space() under httpd:
<?php echo disk_free_space('/'); ?>
prints:
324881317888
I double-checked and the space available is that of the mount available to the
chroot. Here’s the output of df ("disk free") in kilobyte blocks on the mount
which contains the chroot’d directory:
$ df -k /web-server Filesystem 1K-blocks Used Avail Capacity Mounted on /dev/sd1a 969081624 603360632 317266912 66% /web-server
Does that match the "Avail(able)" kilobytes reported by df?
324881317888 / 1024 = 317266912
Yup!
And here’s how I ended up formatting the byte output to human-readable values (up to Terabytes - I don’t have any Petabyte drives yet). Nothing clever, just a simple loop:
<?php
$bytes = disk_free_space('/');
$units = ['bytes', 'Kb', 'Mb', 'Gb', 'Tb'];
$i=0;
while($bytes >= 1024){
$bytes /= 1024;
$i++;
}
$free_space = round($bytes, 1);
echo "Free space on /web-server: <b>{$free_space} {$units[$i]}</b>";
?>
Which prints 324881317888 bytes of free space like so: