PHP disk_total_space() 函数

说明: disk_total_space() 函数返回指定目录所在磁盘分区的总空间(以字节为单位)。

语法

float|false disk_total_space ( string $directory )

参数说明

参数 描述 必需
directory 文件系统目录或磁盘分区
可以是绝对路径或相对路径

返回值

  • 成功时返回总空间的字节数(浮点数)
  • 失败时返回 FALSE

注意事项

  • Windows系统上,参数可以是盘符(如:"C:")或目录
  • Unix/Linux系统上,参数必须是挂载点的目录路径
  • 返回的是总空间的字节数,不是格式化后的字符串
  • 结果受文件系统缓存影响,可能不是实时精确值
  • 需要相应目录的读取权限
  • 对于某些网络文件系统或特殊设备,可能无法获取准确信息
  • 与disk_free_space()配合使用可以计算已用空间

磁盘空间计算公式

基本计算公式:
  • 总空间 = disk_total_space($directory)
  • 可用空间 = disk_free_space($directory)
  • 已用空间 = 总空间 - 可用空间
  • 使用率 = (已用空间 / 总空间) × 100%
  • 可用率 = (可用空间 / 总空间) × 100%

示例

示例 1:基本使用

<?php
// 获取当前目录所在磁盘的总空间
$directory = ".";
$total_space = disk_total_space($directory);

if ($total_space !== false) {
    echo "当前目录所在磁盘的总空间: " . $total_space . " 字节\n";
    echo "总空间: " . round($total_space / 1024 / 1024 / 1024, 2) . " GB";
} else {
    echo "无法获取磁盘总空间信息";
}
?>

示例 2:结合disk_free_space()使用

<?php
/**
 * 获取完整的磁盘空间信息
 */
function get_disk_space_info($directory = '.') {
    // 获取总空间和可用空间
    $total_space = disk_total_space($directory);
    $free_space = disk_free_space($directory);

    if ($total_space === false || $free_space === false) {
        return false;
    }

    // 计算已用空间
    $used_space = $total_space - $free_space;

    // 计算使用率
    $usage_percentage = ($used_space / $total_space) * 100;
    $free_percentage = 100 - $usage_percentage;

    return [
        'total' => $total_space,
        'free' => $free_space,
        'used' => $used_space,
        'usage_percentage' => $usage_percentage,
        'free_percentage' => $free_percentage,
        'directory' => $directory
    ];
}

/**
 * 格式化磁盘空间信息为易读格式
 */
function format_disk_info($disk_info) {
    if (!$disk_info) {
        return "无法获取磁盘信息";
    }

    $formatted = [
        'total' => format_bytes($disk_info['total']),
        'free' => format_bytes($disk_info['free']),
        'used' => format_bytes($disk_info['used']),
        'usage_percentage' => round($disk_info['usage_percentage'], 2) . '%',
        'free_percentage' => round($disk_info['free_percentage'], 2) . '%'
    ];

    return $formatted;
}

/**
 * 字节格式化函数
 */
function format_bytes($bytes, $precision = 2) {
    $units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

    if ($bytes == 0) {
        return '0 B';
    }

    $bytes = abs($bytes);
    $base = log($bytes, 1024);
    $floor = floor($base);

    // 防止索引超出数组范围
    $unit_index = min($floor, count($units) - 1);

    return round(pow(1024, $base - $unit_index), $precision) . ' ' . $units[$unit_index];
}

// 使用示例
$disk_info = get_disk_space_info("/");
if ($disk_info) {
    $formatted = format_disk_info($disk_info);

    echo "磁盘空间信息(目录: {$disk_info['directory']}):\n";
    echo "=================================\n";
    echo "总空间: " . $formatted['total'] . "\n";
    echo "已用空间: " . $formatted['used'] . "\n";
    echo "可用空间: " . $formatted['free'] . "\n";
    echo "使用率: " . $formatted['usage_percentage'] . "\n";
    echo "可用率: " . $formatted['free_percentage'] . "\n";

    // 生成进度条样式
    echo "\n使用情况进度条:\n";
    $usage_bar = str_repeat("█", round($disk_info['usage_percentage'] / 5));
    $free_bar = str_repeat("░", round($disk_info['free_percentage'] / 5));
    echo "[" . $usage_bar . $free_bar . "]";
} else {
    echo "无法获取磁盘空间信息";
}
?>

示例 3:多磁盘空间监控

<?php
/**
 * 多磁盘空间监控类
 */
class MultiDiskMonitor {
    private $disks = [];
    private $threshold = 90; // 使用率阈值

    public function __construct($disks = null, $threshold = 90) {
        $this->disks = $disks ?: $this->detectDisks();
        $this->threshold = $threshold;
    }

    /**
     * 自动检测系统中的磁盘
     */
    private function detectDisks() {
        $disks = [];

        // Windows系统
        if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
            for ($drive = 'C'; $drive <= 'Z'; $drive++) {
                $path = $drive . ':';
                if (is_dir($path)) {
                    $disks[$path] = "磁盘 $drive";
                }
            }
        } else {
            // Unix/Linux系统
            $common_mounts = ['/', '/home', '/tmp', '/var', '/usr', '/boot'];
            foreach ($common_mounts as $mount) {
                if (is_dir($mount)) {
                    $disks[$mount] = "挂载点 " . basename($mount);
                }
            }

            // 尝试读取/proc/mounts获取挂载点
            if (file_exists('/proc/mounts')) {
                $mounts = file('/proc/mounts', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
                foreach ($mounts as $mount_line) {
                    $parts = explode(' ', $mount_line);
                    if (count($parts) >= 2) {
                        $mount_point = $parts[1];
                        if (is_dir($mount_point) && !isset($disks[$mount_point])) {
                            $disks[$mount_point] = "挂载点 " . basename($mount_point);
                        }
                    }
                }
            }
        }

        return $disks;
    }

    /**
     * 获取所有磁盘的空间信息
     */
    public function getAllDiskSpace() {
        $results = [];

        foreach ($this->disks as $path => $label) {
            $total = disk_total_space($path);
            $free = disk_free_space($path);

            if ($total === false || $free === false) {
                $results[$path] = [
                    'label' => $label,
                    'status' => 'error',
                    'message' => '无法访问'
                ];
                continue;
            }

            $used = $total - $free;
            $usage_percentage = ($used / $total) * 100;

            $results[$path] = [
                'label' => $label,
                'path' => $path,
                'total' => $total,
                'used' => $used,
                'free' => $free,
                'usage_percentage' => $usage_percentage,
                'free_percentage' => 100 - $usage_percentage,
                'status' => $usage_percentage > $this->threshold ? 'warning' : 'normal',
                'formatted' => [
                    'total' => $this->formatBytes($total),
                    'used' => $this->formatBytes($used),
                    'free' => $this->formatBytes($free),
                    'usage' => round($usage_percentage, 2) . '%'
                ]
            ];
        }

        // 按使用率降序排序
        uasort($results, function($a, $b) {
            return $b['usage_percentage'] <=> $a['usage_percentage'];
        });

        return $results;
    }

    /**
     * 获取磁盘空间使用统计
     */
    public function getStatistics() {
        $disk_info = $this->getAllDiskSpace();

        $stats = [
            'total_disks' => count($disk_info),
            'total_space' => 0,
            'total_used' => 0,
            'total_free' => 0,
            'warning_disks' => 0,
            'error_disks' => 0,
            'disks' => []
        ];

        foreach ($disk_info as $path => $info) {
            if ($info['status'] === 'normal' || $info['status'] === 'warning') {
                $stats['total_space'] += $info['total'];
                $stats['total_used'] += $info['used'];
                $stats['total_free'] += $info['free'];

                if ($info['status'] === 'warning') {
                    $stats['warning_disks']++;
                }
            } elseif ($info['status'] === 'error') {
                $stats['error_disks']++;
            }

            $stats['disks'][$path] = $info;
        }

        if ($stats['total_space'] > 0) {
            $stats['total_usage_percentage'] = ($stats['total_used'] / $stats['total_space']) * 100;
            $stats['formatted'] = [
                'total_space' => $this->formatBytes($stats['total_space']),
                'total_used' => $this->formatBytes($stats['total_used']),
                'total_free' => $this->formatBytes($stats['total_free']),
                'total_usage' => round($stats['total_usage_percentage'], 2) . '%'
            ];
        }

        return $stats;
    }

    /**
     * 生成HTML报告
     */
    public function generateHtmlReport() {
        $disk_info = $this->getAllDiskSpace();
        $stats = $this->getStatistics();

        $html = '<div class="multi-disk-report">';
        $html .= '<h3><i class="fas fa-hdd"></i> 多磁盘空间监控报告</h3>';

        // 总体统计
        $html .= '<div class="card mb-4">';
        $html .= '<div class="card-body">';
        $html .= '<h5>总体统计</h5>';
        $html .= '<p>监控磁盘数量: ' . $stats['total_disks'] . '</p>';

        if (isset($stats['formatted'])) {
            $html .= '<p>总空间: ' . $stats['formatted']['total_space'] . '</p>';
            $html .= '<p>已用空间: ' . $stats['formatted']['total_used'] . '</p>';
            $html .= '<p>可用空间: ' . $stats['formatted']['total_free'] . '</p>';
            $html .= '<p>总使用率: ' . $stats['formatted']['total_usage'] . '</p>';
        }

        if ($stats['warning_disks'] > 0) {
            $html .= '<div class="alert alert-warning">';
            $html .= '<i class="fas fa-exclamation-triangle"></i> ' . $stats['warning_disks'] . ' 个磁盘空间告警';
            $html .= '</div>';
        }

        if ($stats['error_disks'] > 0) {
            $html .= '<div class="alert alert-danger">';
            $html .= '<i class="fas fa-times-circle"></i> ' . $stats['error_disks'] . ' 个磁盘无法访问';
            $html .= '</div>';
        }

        $html .= '</div></div>';

        // 详细磁盘信息表格
        $html .= '<h5>详细磁盘信息</h5>';
        $html .= '<table class="table table-striped">';
        $html .= '<thead><tr>';
        $html .= '<th>磁盘</th><th>路径</th><th>总空间</th>';
        $html .= '<th>已用空间</th><th>可用空间</th><th>使用率</th><th>状态</th>';
        $html .= '</tr></thead>';
        $html .= '<tbody>';

        foreach ($disk_info as $info) {
            $status_class = $info['status'] === 'warning' ? 'warning' :
                           ($info['status'] === 'error' ? 'danger' : 'success');
            $status_text = $info['status'] === 'warning' ? '告警' :
                          ($info['status'] === 'error' ? '错误' : '正常');

            $html .= '<tr>';
            $html .= '<td>' . $info['label'] . '</td>';
            $html .= '<td><code>' . $info['path'] . '</code></td>';
            $html .= '<td>' . $info['formatted']['total'] . '</td>';
            $html .= '<td>' . $info['formatted']['used'] . '</td>';
            $html .= '<td>' . $info['formatted']['free'] . '</td>';
            $html .= '<td>';
            $html .= '<div class="progress" style="height: 20px;">';
            $html .= '<div class="progress-bar bg-' . $status_class . '" role="progressbar" ';
            $html .= 'style="width: ' . $info['usage_percentage'] . '%">';
            $html .= $info['formatted']['usage'] . '</div></div>';
            $html .= '</td>';
            $html .= '<td><span class="badge bg-' . $status_class . '">' . $status_text . '</span></td>';
            $html .= '</tr>';
        }

        $html .= '</tbody></table>';
        $html .= '</div>';

        return $html;
    }

    /**
     * 字节格式化函数
     */
    private function formatBytes($bytes, $precision = 2) {
        $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 /= pow(1024, $pow);

        return round($bytes, $precision) . ' ' . $units[$pow];
    }
}

// 使用示例
$monitor = new MultiDiskMonitor();
echo "多磁盘空间监控:\n";
$stats = $monitor->getStatistics();

echo "监控磁盘数量: " . $stats['total_disks'] . "\n";
if (isset($stats['formatted'])) {
    echo "总空间: " . $stats['formatted']['total_space'] . "\n";
    echo "总使用率: " . $stats['formatted']['total_usage'] . "\n";
}

// 输出每个磁盘的信息
$disk_info = $monitor->getAllDiskSpace();
foreach ($disk_info as $info) {
    echo "\n" . str_repeat("-", 60) . "\n";
    echo "磁盘: " . $info['label'] . "\n";
    echo "路径: " . $info['path'] . "\n";
    echo "总空间: " . $info['formatted']['total'] . "\n";
    echo "使用率: " . $info['formatted']['usage'] . "\n";
    echo "状态: " . ($info['status'] === 'warning' ? '⚠️ 告警' : ($info['status'] === 'error' ? '❌ 错误' : '✅ 正常'));
}

// 生成HTML报告
// echo $monitor->generateHtmlReport();
?>

示例 4:磁盘容量规划工具

<?php
/**
 * 磁盘容量规划工具类
 */
class DiskCapacityPlanner {
    private $directory;
    private $growth_rate = 0.1; // 默认每月10%的增长率

    public function __construct($directory = '.', $growth_rate = 0.1) {
        $this->directory = $directory;
        $this->growth_rate = $growth_rate;
    }

    /**
     * 预测未来磁盘使用情况
     */
    public function forecastUsage($months = 12) {
        $total = disk_total_space($this->directory);
        $free = disk_free_space($this->directory);

        if ($total === false || $free === false) {
            return false;
        }

        $used = $total - $free;
        $current_usage_percentage = ($used / $total) * 100;

        $forecast = [
            'current' => [
                'total' => $total,
                'used' => $used,
                'free' => $free,
                'usage_percentage' => $current_usage_percentage,
                'formatted' => $this->formatDiskInfo($total, $used, $free)
            ],
            'months' => [],
            'warnings' => []
        ];

        // 按月预测
        $projected_used = $used;
        for ($month = 1; $month <= $months; $month++) {
            // 按增长率增加使用量
            $projected_used = $projected_used * (1 + $this->growth_rate);

            // 不能超过总空间
            if ($projected_used > $total) {
                $projected_used = $total;
            }

            $projected_free = $total - $projected_used;
            $projected_usage_percentage = ($projected_used / $total) * 100;

            $forecast['months'][$month] = [
                'used' => $projected_used,
                'free' => $projected_free,
                'usage_percentage' => $projected_usage_percentage,
                'formatted' => $this->formatDiskInfo($total, $projected_used, $projected_free)
            ];

            // 检查是否需要告警
            if ($projected_usage_percentage >= 90) {
                $forecast['warnings'][] = "第 {$month} 个月后,磁盘使用率将达到 " .
                                          round($projected_usage_percentage, 1) . "%";
            }

            if ($projected_usage_percentage >= 100) {
                $forecast['warnings'][] = "⚠️ 警告:第 {$month} 个月后,磁盘将完全写满!";
                break;
            }
        }

        return $forecast;
    }

    /**
     * 计算建议的扩容时间
     */
    public function suggestExpansion($warning_threshold = 90) {
        $forecast = $this->forecastUsage(60); // 预测5年

        if (!$forecast) {
            return false;
        }

        $suggestions = [];

        foreach ($forecast['months'] as $month => $data) {
            if ($data['usage_percentage'] >= $warning_threshold) {
                $suggestions['warning_month'] = $month;
                $suggestions['estimated_date'] = date('Y-m-d', strtotime("+{$month} months"));
                $suggestions['usage_at_warning'] = round($data['usage_percentage'], 1) . '%';
                break;
            }
        }

        if (empty($suggestions)) {
            $suggestions['message'] = "在可预见的未来(5年内)无需扩容";
            $suggestions['max_usage'] = round(end($forecast['months'])['usage_percentage'], 1) . '%';
        } else {
            $suggestions['message'] = "建议在第 {$suggestions['warning_month']} 个月之前进行扩容";
        }

        return array_merge($suggestions, [
            'growth_rate' => $this->growth_rate * 100 . '%',
            'current_usage' => $forecast['current']['formatted']['usage_percentage']
        ]);
    }

    /**
     * 生成预测报告
     */
    public function generateForecastReport($months = 12) {
        $forecast = $this->forecastUsage($months);

        if (!$forecast) {
            return "无法生成预测报告";
        }

        $report = "磁盘容量预测报告\n";
        $report .= "=================================\n";
        $report .= "预测目录: " . $this->directory . "\n";
        $report .= "月增长率: " . ($this->growth_rate * 100) . "%\n";
        $report .= "预测周期: " . $months . " 个月\n\n";

        $report .= "当前状态:\n";
        $report .= "总空间: " . $forecast['current']['formatted']['total'] . "\n";
        $report .= "已用空间: " . $forecast['current']['formatted']['used'] . "\n";
        $report .= "可用空间: " . $forecast['current']['formatted']['free'] . "\n";
        $report .= "使用率: " . $forecast['current']['formatted']['usage_percentage'] . "\n\n";

        $report .= "未来预测:\n";
        $report .= "月份 | 使用率 | 已用空间 | 可用空间\n";
        $report .= str_repeat("-", 60) . "\n";

        foreach ($forecast['months'] as $month => $data) {
            $report .= sprintf(
                "%4d | %6.1f%% | %10s | %10s\n",
                $month,
                $data['usage_percentage'],
                $data['formatted']['used'],
                $data['formatted']['free']
            );
        }

        if (!empty($forecast['warnings'])) {
            $report .= "\n⚠️ 警告信息:\n";
            foreach ($forecast['warnings'] as $warning) {
                $report .= "- " . $warning . "\n";
            }
        }

        return $report;
    }

    /**
     * 格式化磁盘信息
     */
    private function formatDiskInfo($total, $used, $free) {
        return [
            'total' => $this->formatBytes($total),
            'used' => $this->formatBytes($used),
            'free' => $this->formatBytes($free),
            'usage_percentage' => round(($used / $total) * 100, 2) . '%'
        ];
    }

    /**
     * 字节格式化函数
     */
    private function formatBytes($bytes, $precision = 2) {
        $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 /= pow(1024, $pow);

        return round($bytes, $precision) . ' ' . $units[$pow];
    }
}

// 使用示例
$planner = new DiskCapacityPlanner('/', 0.05); // 根目录,每月5%增长率

echo "磁盘容量规划报告\n";
echo "================\n\n";

// 生成12个月的预测报告
$report = $planner->generateForecastReport(12);
echo $report;

// 获取扩容建议
$suggestion = $planner->suggestExpansion(85); // 85%为告警阈值
if ($suggestion) {
    echo "\n扩容建议:\n";
    echo "========\n";
    echo $suggestion['message'] . "\n";

    if (isset($suggestion['warning_month'])) {
        echo "预计告警时间: 第 " . $suggestion['warning_month'] . " 个月 (" .
             $suggestion['estimated_date'] . ")\n";
        echo "告警时使用率: " . $suggestion['usage_at_warning'] . "\n";
    }

    echo "当前使用率: " . $suggestion['current_usage'] . "\n";
    echo "月增长率: " . $suggestion['growth_rate'] . "\n";
}
?>

示例 5:磁盘性能基准测试

<?php
/**
 * 磁盘性能测试类
 */
class DiskBenchmark {
    private $test_file_size = 1048576; // 1MB测试文件
    private $iterations = 5;

    public function __construct($test_file_size = 1048576, $iterations = 5) {
        $this->test_file_size = $test_file_size;
        $this->iterations = $iterations;
    }

    /**
     * 执行磁盘读写性能测试
     */
    public function runBenchmark($directory = '.') {
        $results = [
            'directory' => $directory,
            'total_space' => disk_total_space($directory),
            'free_space' => disk_free_space($directory),
            'write_speeds' => [],
            'read_speeds' => [],
            'average_write_speed' => 0,
            'average_read_speed' => 0
        ];

        if ($results['total_space'] === false || $results['free_space'] === false) {
            return false;
        }

        // 确保测试文件大小不超过可用空间的10%
        $max_test_size = $results['free_space'] * 0.1;
        $test_size = min($this->test_file_size, $max_test_size);

        $test_file = rtrim($directory, '/') . '/benchmark_test.tmp';

        // 写入测试
        $total_write_time = 0;
        for ($i = 0; $i < $this->iterations; $i++) {
            $write_speed = $this->testWriteSpeed($test_file, $test_size);
            if ($write_speed !== false) {
                $results['write_speeds'][] = $write_speed;
                $total_write_time += $write_speed['time'];
            }

            // 清理文件,为下一次测试准备
            if (file_exists($test_file)) {
                unlink($test_file);
            }
        }

        // 读取测试(需要先创建文件)
        $test_data = str_repeat('A', $test_size);
        file_put_contents($test_file, $test_data);

        $total_read_time = 0;
        for ($i = 0; $i < $this->iterations; $i++) {
            $read_speed = $this->testReadSpeed($test_file, $test_size);
            if ($read_speed !== false) {
                $results['read_speeds'][] = $read_speed;
                $total_read_time += $read_speed['time'];
            }
        }

        // 清理测试文件
        if (file_exists($test_file)) {
            unlink($test_file);
        }

        // 计算平均值
        if (count($results['write_speeds']) > 0) {
            $results['average_write_speed'] = [
                'speed_mb_per_sec' => array_sum(array_column($results['write_speeds'], 'speed_mb_per_sec')) /
                                     count($results['write_speeds']),
                'time' => $total_write_time / count($results['write_speeds'])
            ];
        }

        if (count($results['read_speeds']) > 0) {
            $results['average_read_speed'] = [
                'speed_mb_per_sec' => array_sum(array_column($results['read_speeds'], 'speed_mb_per_sec')) /
                                     count($results['read_speeds']),
                'time' => $total_read_time / count($results['read_speeds'])
            ];
        }

        // 添加格式化信息
        $results['formatted'] = [
            'total_space' => $this->formatBytes($results['total_space']),
            'free_space' => $this->formatBytes($results['free_space']),
            'usage_percentage' => round((($results['total_space'] - $results['free_space']) /
                                        $results['total_space']) * 100, 2) . '%',
            'average_write_speed' => isset($results['average_write_speed']['speed_mb_per_sec']) ?
                                   round($results['average_write_speed']['speed_mb_per_sec'], 2) . ' MB/s' : 'N/A',
            'average_read_speed' => isset($results['average_read_speed']['speed_mb_per_sec']) ?
                                  round($results['average_read_speed']['speed_mb_per_sec'], 2) . ' MB/s' : 'N/A'
        ];

        return $results;
    }

    /**
     * 测试写入速度
     */
    private function testWriteSpeed($filename, $size) {
        $data = str_repeat('A', $size);

        $start_time = microtime(true);
        $bytes_written = file_put_contents($filename, $data, LOCK_EX);
        $end_time = microtime(true);

        if ($bytes_written === false) {
            return false;
        }

        $time_taken = $end_time - $start_time;
        $speed_mb_per_sec = ($size / 1024 / 1024) / $time_taken;

        return [
            'time' => $time_taken,
            'size' => $size,
            'bytes_written' => $bytes_written,
            'speed_mb_per_sec' => $speed_mb_per_sec
        ];
    }

    /**
     * 测试读取速度
     */
    private function testReadSpeed($filename, $size) {
        $start_time = microtime(true);
        $data = file_get_contents($filename);
        $end_time = microtime(true);

        if ($data === false) {
            return false;
        }

        $time_taken = $end_time - $start_time;
        $actual_size = strlen($data);
        $speed_mb_per_sec = ($actual_size / 1024 / 1024) / $time_taken;

        return [
            'time' => $time_taken,
            'expected_size' => $size,
            'actual_size' => $actual_size,
            'speed_mb_per_sec' => $speed_mb_per_sec
        ];
    }

    /**
     * 生成性能报告
     */
    public function generateBenchmarkReport($directory = '.') {
        $results = $this->runBenchmark($directory);

        if (!$results) {
            return "无法执行性能测试";
        }

        $report = "磁盘性能基准测试报告\n";
        $report .= "=================================\n";
        $report .= "测试目录: " . $results['directory'] . "\n";
        $report .= "总空间: " . $results['formatted']['total_space'] . "\n";
        $report .= "可用空间: " . $results['formatted']['free_space'] . "\n";
        $report .= "使用率: " . $results['formatted']['usage_percentage'] . "\n\n";

        $report .= "写入性能测试 (" . $this->iterations . " 次迭代):\n";
        $report .= "迭代 | 时间(秒) | 速度(MB/秒)\n";
        $report .= str_repeat("-", 40) . "\n";

        foreach ($results['write_speeds'] as $i => $write) {
            $report .= sprintf("%4d | %9.4f | %12.2f\n",
                $i + 1, $write['time'], $write['speed_mb_per_sec']);
        }

        $report .= sprintf("\n平均写入速度: %s\n\n",
            $results['formatted']['average_write_speed']);

        $report .= "读取性能测试 (" . $this->iterations . " 次迭代):\n";
        $report .= "迭代 | 时间(秒) | 速度(MB/秒)\n";
        $report .= str_repeat("-", 40) . "\n";

        foreach ($results['read_speeds'] as $i => $read) {
            $report .= sprintf("%4d | %9.4f | %12.2f\n",
                $i + 1, $read['time'], $read['speed_mb_per_sec']);
        }

        $report .= sprintf("\n平均读取速度: %s\n",
            $results['formatted']['average_read_speed']);

        // 性能评级
        $avg_speed = max(
            isset($results['average_write_speed']['speed_mb_per_sec']) ?
            $results['average_write_speed']['speed_mb_per_sec'] : 0,
            isset($results['average_read_speed']['speed_mb_per_sec']) ?
            $results['average_read_speed']['speed_mb_per_sec'] : 0
        );

        $report .= "\n性能评级: ";
        if ($avg_speed > 100) {
            $report .= "⭐️⭐️⭐️⭐️⭐️ (极快 - 固态硬盘)\n";
        } elseif ($avg_speed > 50) {
            $report .= "⭐️⭐️⭐️⭐️ (快速 - 高速机械硬盘)\n";
        } elseif ($avg_speed > 20) {
            $report .= "⭐️⭐️⭐️ (中等 - 标准机械硬盘)\n";
        } elseif ($avg_speed > 5) {
            $report .= "⭐️⭐️ (较慢 - 旧式机械硬盘)\n";
        } else {
            $report .= "⭐️ (非常慢 - 网络存储或过载磁盘)\n";
        }

        return $report;
    }

    /**
     * 字节格式化函数
     */
    private function formatBytes($bytes, $precision = 2) {
        $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 /= pow(1024, $pow);

        return round($bytes, $precision) . ' ' . $units[$pow];
    }
}

// 使用示例
$benchmark = new DiskBenchmark(5242880, 3); // 5MB测试文件,3次迭代
echo $benchmark->generateBenchmarkReport('/tmp');
?>

与disk_free_space()的区别

函数 描述 返回值 常用场景
disk_total_space() 获取磁盘总容量 总字节数(浮点数) 容量规划、资源监控、系统管理
disk_free_space() 获取磁盘可用空间 可用字节数(浮点数) 空间检查、备份验证、上传限制

相关函数

最佳实践
  1. 组合使用:通常与disk_free_space()一起使用,计算磁盘使用率
  2. 错误处理:始终检查返回值是否为false,处理可能的错误
  3. 权限管理:确保对目标目录有读取权限
  4. 缓存意识:结果可能被缓存,对于需要实时数据的场景要谨慎
  5. 格式化输出:将字节数转换为易读的格式(KB、MB、GB等)
  6. 跨平台考虑:注意Windows和Unix/Linux系统之间的路径差异
  7. 监控集成:将磁盘空间监控集成到系统监控工具中
  8. 容量规划:定期分析磁盘使用趋势,进行容量规划
实际应用场景
1. 系统健康检查脚本
<?php
// 系统健康检查
function system_health_check() {
    $checks = [];

    // 检查磁盘空间
    $disks = ['/', '/home', '/tmp', '/var'];
    foreach ($disks as $disk) {
        if (is_dir($disk)) {
            $total = disk_total_space($disk);
            $free = disk_free_space($disk);

            if ($total !== false && $free !== false) {
                $usage = (($total - $free) / $total) * 100;
                $checks[] = [
                    'component' => '磁盘空间',
                    'location' => $disk,
                    'status' => $usage > 90 ? 'critical' : ($usage > 80 ? 'warning' : 'ok'),
                    'details' => '使用率: ' . round($usage, 1) . '%'
                ];
            }
        }
    }

    return $checks;
}

// 执行健康检查
$health = system_health_check();
foreach ($health as $check) {
    $icon = $check['status'] === 'ok' ? '✅' : ($check['status'] === 'warning' ? '⚠️' : '❌');
    echo "{$icon} {$check['component']} ({$check['location']}): {$check['details']}\n";
}
?>
2. 服务器资源监控面板
<?php
// 生成服务器资源摘要
function server_resources_summary() {
    $summary = [
        'disks' => [],
        'memory' => [], // 可以添加内存信息
        'load' => []    // 可以添加负载信息
    ];

    // 获取磁盘信息
    $paths = ['/', '/home', '/tmp'];
    if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
        $paths = ['C:', 'D:', 'E:'];
    }

    foreach ($paths as $path) {
        if (is_dir($path)) {
            $total = disk_total_space($path);
            $free = disk_free_space($path);

            if ($total !== false && $free !== false) {
                $summary['disks'][$path] = [
                    'total' => format_bytes($total),
                    'free' => format_bytes($free),
                    'used' => format_bytes($total - $free),
                    'usage' => round((($total - $free) / $total) * 100, 1) . '%'
                ];
            }
        }
    }

    return $summary;
}

// 辅助函数:格式化字节
function format_bytes($bytes) {
    $units = ['B', 'KB', 'MB', 'GB', 'TB'];
    $bytes = max($bytes, 0);
    $i = floor(($bytes ? log($bytes) : 0) / log(1024));
    $i = min($i, count($units) - 1);
    $bytes /= pow(1024, $i);

    return round($bytes, 2) . ' ' . $units[$i];
}
?>