NetworkSpeedMonitor.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. class NetworkSpeedMonitor
  3. {
  4. //获取内存使用情况
  5. public static function getMemoryUsage(): array
  6. {
  7. $memoryInfo = shell_exec('free -b');
  8. if ($memoryInfo !== false) {
  9. $lines = explode("\n", $memoryInfo);
  10. $memoryData = preg_split('/\s+/', $lines[1]);
  11. $totalMemory = $memoryData[1];
  12. $usedMemory = $memoryData[2];
  13. return ['total' => (double)$totalMemory, 'used' => (double)$usedMemory, 'percentage' => (double)number_format($usedMemory / $totalMemory * 100, 2)];
  14. } else {
  15. return ['total' => 0, 'used' => 0, 'percentage' => 0];
  16. }
  17. }
  18. /**
  19. * 格式化字节数为更人性化的显示方式
  20. *
  21. * @param int $bytes 字节数
  22. * @return string 格式化后的字符串
  23. */
  24. public static function formatBytes(int $bytes): string
  25. {
  26. $units = array('Byte', 'KB', 'MB', 'GB', 'TB');
  27. $index = 0;
  28. while ($bytes >= 1024 && $index < count($units) - 1) {
  29. $bytes /= 1024;
  30. $index++;
  31. }
  32. return round($bytes, 2) . ' ' . $units[$index];
  33. }
  34. static function getDiskData(): array
  35. {
  36. $df_output = shell_exec('df -h');
  37. $lines = explode("\n", $df_output);
  38. $disk_usage = array();
  39. for ($i = 1; $i < count($lines); $i++) {
  40. if (empty(trim($lines[$i]))) {
  41. continue;
  42. }
  43. // 分割每一行的数据,以空格作为分隔符
  44. $data = preg_split('/\s+/', $lines[$i]);
  45. // 提取所需的信息,例如文件系统路径、总大小、已用空间、可用空间、使用率
  46. $filesystem = $data[0];
  47. $total_size = $data[1];
  48. $used_space = $data[2];
  49. $available_space = $data[3];
  50. $usage_percent = $data[4];
  51. $mounts = $data[5];
  52. if ($mounts == "/") {
  53. // 将信息存储到关联数组中
  54. $disk_usage[] = array(
  55. 'filesystem' => $filesystem,
  56. 'total_size' => $total_size,
  57. 'used_space' => $used_space,
  58. 'available_space' => $available_space,
  59. 'usage_percent' => (double)preg_replace("#%#", '', $usage_percent), //去掉内容中的%,
  60. 'mounted'=>$mounts
  61. );
  62. }
  63. }
  64. return $disk_usage;
  65. }
  66. }