Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Linux Disk Usage PHP Script
<?php
include_once './vendor/autoload.php';
use jc21\CliTable;
use jc21\CliTableManipulator;
// HOW TO USE:
// copy script ( linux-disk-usage.php ) to a folder on your system and cd to that folder
// composer require jc21/clitable
// php linux-disk-usage.php
function bytesToHumanReadable($bytes, $decimalPlaces = 2) {
$type = array("bytes", "KB", "MB", "GB", "TB", "PB", "EXB", "ZB", "YB");
$index = 0;
while ($bytes >= 1024) {
$bytes /= 1024;
$index++;
}
$formattedBytes = number_format(((float) $bytes), $decimalPlaces);
return ("" . $formattedBytes . " " . $type[$index]);
}
function getListOfFileSystems() {
$mounted_file_systems = [];
exec('findmnt -l -o TARGET', $mounted_file_systems);
array_shift($mounted_file_systems); // remove output header
sort($mounted_file_systems);
return $mounted_file_systems;
}
function generateDiskUsageData() {
$diskUsageData = [];
foreach (getListOfFileSystems() as $mounted_file_system) {
$freeSpace = disk_free_space($mounted_file_system);
$totalSpace = disk_total_space($mounted_file_system);
$usedSpacePercentage = ($totalSpace <= 0) ? 0 : (($totalSpace - $freeSpace) / $totalSpace) * 100;
$diskUsageData[] = [
'fs_name' => $mounted_file_system,
'disk_free_space' => $freeSpace,
'disk_total_space' => $totalSpace,
'used_space_percent' => $usedSpacePercentage,
];
}
return $diskUsageData;
}
function generateDiskUsageDataHumanReadable() {
$diskUsageData = generateDiskUsageData();
foreach ($diskUsageData as $key => $data) {
$diskUsageData[$key]['disk_free_space'] = bytesToHumanReadable($data['disk_free_space']);
$diskUsageData[$key]['disk_total_space'] = bytesToHumanReadable($data['disk_total_space']);
}
return $diskUsageData;
}
function diskUsageInCliFormat($humanReadable=true) {
$table = new CliTable;
$table->setTableColor('blue');
$table->setHeaderColor('cyan');
$table->addField('File System', 'fs_name', false, 'white');
$table->addField('Used Space %', 'used_space_percent', new CliTableManipulator('percent'), 'white');
$table->addField('Free Space', 'disk_free_space', false, 'white');
$table->addField('Total Space', 'disk_total_space', false, 'white');
$table->injectData($humanReadable ? generateDiskUsageDataHumanReadable() : generateDiskUsageData());
$table->display();
}
diskUsageInCliFormat(true);
diskUsageInCliFormat(false);
@rotexdegba

This comment has been minimized.

Copy link
Owner Author

@rotexdegba rotexdegba commented Apr 20, 2020

How to Use

  • copy script ( linux-disk-usage.php ) to a folder on your system and cd to that folder
  • composer require jc21/clitable
  • php linux-disk-usage.php
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.