Learn how to monitor system resources in PHP using shell scripting. Track CPU usage, memory consumption, disk space, and active processes dynamically.
Introduction
Monitoring CPU, memory, and disk usage is essential for server performance optimization, troubleshooting, and automated alerts. Instead of manually checking system resources, PHP and shell scripting allow real-time tracking of system health.
With PHP and shell scripting, you can:
- Retrieve CPU usage dynamically
- Monitor memory consumption and available RAM
- Track disk space usage in real-time
- List running processes on a server
- Automate alerts for high resource usage
This guide covers:
- Retrieving system resource metrics using shell commands
- Displaying real-time CPU, memory, and disk usage in PHP
- Automating resource monitoring and alerts
- Using cron jobs for scheduled monitoring
1. Checking CPU Usage with PHP and Shell Commands
Basic CPU Usage Monitoring
$output = shell_exec("top -bn1 | grep 'Cpu(s)'");
echo "<pre>$output</pre>";
Using mpstat for More Details
$output = shell_exec("mpstat 1 1");
echo "<pre>$output</pre>";
Why Monitor CPU Usage?
- Detects high CPU load due to resource-intensive processes
- Helps optimize performance and avoid server slowdowns
2. Monitoring Memory Usage in PHP
Checking Free Memory Using Shell Commands
$output = shell_exec("free -m");
echo "<pre>$output</pre>";
Extracting Available Memory Only
$output = shell_exec("grep MemAvailable /proc/meminfo | awk '{print $2}'");
echo "Available Memory: " . ($output / 1024) . " MB";
Why Monitor Memory Usage?
- Prevents server crashes due to memory exhaustion
- Helps identify memory leaks in applications
3. Checking Disk Space Usage in PHP
Displaying Disk Usage for All Mounted Partitions
$output = shell_exec("df -h");
echo "<pre>$output</pre>";
Getting Disk Usage for a Specific Directory
$directory = "/var/www/html";
$output = shell_exec("du -sh $directory");
echo "<pre>$output</pre>";
Why Monitor Disk Usage?
- Prevents disk space exhaustion
- Helps identify large log files or unnecessary data
4. Listing Running Processes in PHP
Displaying Active Processes Using ps
$output = shell_exec("ps aux --sort=-%mem | head -10");
echo "<pre>$output</pre>";
Filtering Processes by CPU Usage
$output = shell_exec("ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%cpu | head");
echo "<pre>$output</pre>";
Why Monitor Active Processes?
- Identifies CPU-intensive applications
- Helps troubleshoot server slowdowns
5. Creating a System Resource Monitoring Dashboard in PHP
Example: Displaying CPU, Memory, and Disk Usage in One View
$cpu = shell_exec("top -bn1 | grep 'Cpu(s)'");
$memory = shell_exec("free -m");
$disk = shell_exec("df -h");
echo "<h2>System Resource Monitoring</h2>";
echo "<h3>CPU Usage:</h3><pre>$cpu</pre>";
echo "<h3>Memory Usage:</h3><pre>$memory</pre>";
echo "<h3>Disk Usage:</h3><pre>$disk</pre>";
Why Use a Dashboard?
- Provides real-time server monitoring
- Helps detect issues before they cause failures
6. Automating System Monitoring with Cron Jobs
To automate resource tracking, schedule a cron job to log usage data.
crontab -e
Add the following to run every 5 minutes:
*/5 * * * * php /var/www/html/monitor_resources.php >> /var/log/resource_monitor.log 2>&1
Why Use Cron Jobs?
- Allows continuous system health tracking
- Logs resource usage for analysis
7. Sending Alerts When System Resources Exceed Limits
Example: Alert When CPU Usage is Too High
$cpuUsage = shell_exec("top -bn1 | grep 'Cpu(s)' | awk '{print $2}'");
if ($cpuUsage > 80) {
mail("admin@example.com", "High CPU Alert", "CPU usage is at $cpuUsage%");
}
Example: Alert When Disk Space is Low
$diskUsage = shell_exec("df / | grep / | awk '{print $5}' | sed 's/%//g'");
if ($diskUsage > 90) {
mail("admin@example.com", "Low Disk Space Alert", "Disk usage is at $diskUsage%");
}
Why Automate Alerts?
- Prevents server crashes due to resource exhaustion
- Helps quickly respond to performance issues
8. Using a Bash Script for System Monitoring
PHP Code to Trigger the Monitoring Script
shell_exec("bash /scripts/monitor.sh");
echo "System monitoring script executed.";
Bash Script (monitor.sh)
#!/bin/bash
echo "System Monitoring Report - $(date)"
echo "CPU Usage:"
top -bn1 | grep "Cpu(s)"
echo "Memory Usage:"
free -m
echo "Disk Usage:"
df -h
Why Use Bash for Monitoring?
- More efficient than running multiple PHP shell_exec calls
- Provides real-time system monitoring with one command
9. Creating a Web API for System Monitoring
To allow remote monitoring via an API, return JSON data:
$data = [
'cpu' => shell_exec("top -bn1 | grep 'Cpu(s)'"),
'memory' => shell_exec("free -m"),
'disk' => shell_exec("df -h")
];
header('Content-Type: application/json');
echo json_encode($data);
Why Use an API?
- Enables remote server monitoring
- Integrates with third-party monitoring tools
10. Best Practices for System Resource Monitoring in PHP
- Use cron jobs to automate monitoring and logging
- Trigger alerts when resources exceed safe limits
- Store logs for long-term performance analysis
- Optimize scripts to minimize system load
- Secure monitoring APIs to prevent unauthorized access
Conclusion
Monitoring system resources using PHP and shell scripting ensures efficient server management, prevents resource exhaustion, and enables proactive maintenance.
This guide covered:
- Tracking CPU, memory, and disk usage in PHP
- Listing running processes dynamically
- Automating resource tracking with cron jobs
- Sending alerts for high resource usage
- Building a system monitoring API
By implementing these techniques, PHP applications can efficiently monitor system performance and prevent server failures.