PHP diskfreespace 函数
最后修改于 2025 年 4 月 3 日
PHP 的 diskfreespace 函数用于返回文件系统或磁盘分区的可用空间。它对于在应用程序中监控磁盘使用情况非常有用。
基本定义
diskfreespace 函数返回文件系统或磁盘分区上的可用字节数。它是 disk_free_space 的别名。
语法:diskfreespace(string $directory): float|false。失败时返回 false。directory 参数指定要检查的文件系统。
基本的 diskfreespace 示例
这展示了 diskfreespace 检查可用空间的最简单用法。
basic_diskfreespace.php
<?php
declare(strict_types=1);
$freeSpace = diskfreespace("/");
if ($freeSpace !== false) {
echo "Free space: " . $freeSpace . " bytes";
} else {
echo "Could not determine free space";
}
这会检查根分区的可用空间。结果以字节为单位。为防止错误,请始终检查返回值是否为 false。
将字节转换为人类可读的格式
磁盘空间值转换为 KB、MB 或 GB 时通常更易读。
human_readable.php
<?php
declare(strict_types=1);
function formatBytes(float $bytes, int $precision = 2): string {
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
$bytes /= (1 << (10 * $pow));
return round($bytes, $precision) . ' ' . $units[$pow];
}
$freeSpace = diskfreespace("/");
if ($freeSpace !== false) {
echo "Free space: " . formatBytes($freeSpace);
} else {
echo "Could not determine free space";
}
formatBytes 辅助函数将字节转换为适当的单位。这使得输出对于较大的磁盘空间值更加用户友好。
检查多个分区
您可以检查不同分区或挂载点的可用空间。
multiple_partitions.php
<?php
declare(strict_types=1);
$partitions = ["/", "/home", "/var"];
foreach ($partitions as $partition) {
$freeSpace = diskfreespace($partition);
if ($freeSpace !== false) {
echo "Free space on $partition: " .
round($freeSpace / (1024 * 1024)) . " MB\n";
} else {
echo "Could not check space on $partition\n";
}
}
此示例检查多个分区并将空间显示为兆字节。请注意,分区必须存在且可访问才能使检查成功。
计算可用空间百分比
与 disk_total_space 结合使用以计算可用空间百分比。
percentage_free.php
<?php
declare(strict_types=1);
$directory = "/";
$free = diskfreespace($directory);
$total = disk_total_space($directory);
if ($free !== false && $total !== false) {
$percentFree = ($free / $total) * 100;
echo "Free space: " . round($percentFree, 2) . "%";
} else {
echo "Could not determine disk space";
}
这会计算可用空间的百分比。两个函数都必须成功才能进行计算。结果显示磁盘的填充程度。
Windows 驱动器示例
diskfreespace 也适用于 Windows 驱动器盘符。
windows_drive.php
<?php
declare(strict_types=1);
$drive = "C:";
$freeSpace = diskfreespace($drive);
if ($freeSpace !== false) {
$freeGB = $freeSpace / (1024 * 1024 * 1024);
echo "Free space on $drive: " . round($freeGB, 2) . " GB";
} else {
echo "Could not check space on $drive";
}
在 Windows 上,请指定后跟冒号的驱动器盘符。该示例将字节转换为千兆字节,以便更好地读取典型的 Windows 驱动器大小。
最佳实践
- 错误处理: 始终检查 false 返回值。
- 权限:确保 PHP 可以访问文件系统。
- 缓存:不要频繁调用,因为它会消耗大量文件系统资源。
- 跨平台:适用于 Unix 和 Windows 系统。
- 单位:转换为字节以获得人类可读的输出。
来源
本教程介绍了 PHP 的 diskfreespace 函数,并通过实际示例展示了它在不同场景下的用法。
作者
列出 所有 PHP 文件系统函数。