disk_free_space

Returns the number of free bytes available on the filesystem holding a directory.

Signature
disk_free_space(string $directory): float|false
  • Added in PHP 4.1.0

Parameters

ParameterTypeDescription
$directorystringA directory of the filesystem or disk partition to inspect. Passing a filename instead of a directory has unspecified behaviour that varies between platforms and PHP versions.

Return value

float|falseReturns the number of available bytes as a float, or false on failure.

Errors

Emits an E_WARNING and returns false if the directory cannot be read, does not exist, or is blocked by open_basedir.

disk_free_space() asks the operating system how much room is left on the filesystem that contains the given directory. Note it takes a directory, not a device name — on Unix you pass a mount point such as / or /var, on Windows a drive like C:.

When to reach for it

  • A preflight check before accepting a large upload or writing a big export, so the failure is a clean error rather than a half-written file.
  • Monitoring endpoints and health checks that report remaining capacity.
  • Deciding whether a cache directory should be pruned before more entries are written.

What trips people up

The return type is float, not int, because byte counts on large volumes exceed what a 32-bit int can hold. Do not compare it with === against integers, and format it with number_format() or sprintf('%.2f') rather than relying on echo, which will print something like 1.0E+12 for a large disk.

Check the result with === false. On a full filesystem the function legitimately returns 0.0, and a loose if (!$free) treats that identical to an error.

The number is space available to the calling user. Most Unix filesystems reserve a percentage for root, so a process running as a normal user sees less free space than df reports for root, and the value can be smaller than total minus used.

Example

Example · php
<?php
$dir  = __DIR__;
$free = disk_free_space($dir);

if ($free === false) {
    echo "could not read free space\n";
} else {
    printf("free: %.2f GB\n", $free / 1024 ** 3);

    $needed = 500 * 1024 * 1024;   // 500 MB
    echo $free < $needed
        ? "not enough room for the upload\n"
        : "upload can proceed\n";
}

When to use it

  • Refuse a large file upload with a clear message when the destination partition has less than 500 MB free.
  • Report remaining capacity from a /health endpoint that a monitoring system polls.
  • Trigger cache pruning when free space on the cache partition drops below a threshold.

Frequently asked questions

Why does disk_free_space return a float instead of an int?

Byte counts on modern volumes exceed the range of a 32-bit integer, so PHP returns a float to keep the value representable on every platform. Format it with number_format() or sprintf() rather than echoing it directly.

What is the difference between disk_free_space and diskfreespace?

None — diskfreespace() is simply an alias of disk_free_space(). The underscored name is the documented one and the one to prefer in new code.

Why does the number not match what df reports?

Most Unix filesystems reserve a percentage of blocks for the root user, and disk_free_space() reports what is available to the calling process. It also fails on remote paths, since the filesystem must be reachable locally.

More examples

Percentage used on a partition

Pairing the two functions gives a usage percentage. number_format() is used because echoing a raw float of several hundred billion prints in scientific notation.

Example · php
<?php
$dir   = __DIR__;
$free  = disk_free_space($dir);
$total = disk_total_space($dir);

if ($free === false || $total === false) {
    echo "stat failed\n";
} else {
    printf("used: %.1f%%\n", (1 - $free / $total) * 100);
    printf("free: %s bytes\n", number_format($free, 0, '.', ','));
}

Human-readable formatting

The helper divides down through the unit scale so the output reads as "42.31 GB" instead of a bare float. The === false check keeps a genuinely full disk from printing "unknown".

Example · php
<?php
function human(float $bytes): string {
    $units = ['B', 'KB', 'MB', 'GB', 'TB'];
    $i = 0;
    while ($bytes >= 1024 && $i < count($units) - 1) {
        $bytes /= 1024;
        $i++;
    }
    return sprintf('%.2f %s', $bytes, $units[$i]);
}

$free = disk_free_space('/');
echo $free === false ? "unknown\n" : human($free) . "\n";

Guarding a write with a threshold

Separating the false check from the threshold check means a failed stat raises a different, accurate error than a disk that is simply too full.

Example · php
<?php
$target = __DIR__;
$needed = 100 * 1024 * 1024;
$free   = disk_free_space($target);

if ($free === false) {
    throw new RuntimeException('cannot determine free space');
}
if ($free < $needed) {
    throw new RuntimeException(sprintf(
        'need %d bytes, only %.0f available', $needed, $free
    ));
}
echo "proceeding\n";

Discussion

  • Be the first to comment on this lesson.