要获取磁盘大小,可以使用PHP内置的函数 disk_total_space()
和 disk_free_space()
,它们分别返回指定磁盘的总大小和可用空间,以字节为单位。以下是示例代码:
$disk_total_size = disk_total_space("/"); // 获取根目录的总磁盘空间大小
$disk_free_size = disk_free_space("/"); // 获取根目录的可用磁盘空间大小
// 转换为更易读的格式
$total_size_formatted = formatBytes($disk_total_size);
$free_size_formatted = formatBytes($disk_free_size);
echo "Total disk space: " . $total_size_formatted . "<br>";
echo "Free disk space: " . $free_size_formatted . "<br>";
// 将字节数转换为易读的格式
function formatBytes($bytes, $precision = 2) {
$units = array('B', 'KB', 'MB', 'GB', 'TB');
$bytes = max($bytes, 0);
$power = floor(($bytes ? log($bytes) : 0) / log(1024));
$power = min($power, count($units) - 1);
$bytes /= pow(1024, $power);
return round($bytes, $precision) . ' ' . $units[$power];
}
在上面的示例中,我们使用 disk_total_space()
和 disk_free_space()
函数来获取磁盘的总大小和可用空间。然后,我们使用自定义的 formatBytes()
函数将字节数转换为更易读的格式,例如 "1.23 GB"。最后,我们输出磁盘大小的信息。
请注意,disk_total_space()
和 disk_free_space()
函数可能需要一些时间才能执行,特别是当磁盘容量很大时。因此,在使用这些函数时,应考虑性能问题,并尽可能避免重复调用。
请输入评论内容: