hit or miss

Monitor Disk Space PHP Script

Problem: The /var paritition on my linux box has a habit of rapidly filling up, causing my server to crash. I needed some way to automatically alert myself when the free space on the partition fell below a certain level.

Solution: I wrote a simple script in PHP that sends a text message to my pager if the space used in the /var partition exceeds 12%.

$output = array();
exec("df", $output);
$output = join("\n", $output);
$space = eregi_replace(".* ([0-9]+)% /var.*", "\\1", $output);

if ($space > 12)
{
$pin = "2128232";
$msg = "/var at $space%";
$msg = urlencode($msg);
$url = "http://www.radiocommpaging.com/".
"cgi-bin/webpage/sendpage?pin=$pin&body=$msg";
$fp = @fopen ($url, "r");
}
?>
The script first loads the results of the df command into an array. The output from that command on my linux box looks something like this:

Filesystem 1k-blocks    Used Available Use% Mounted on
/dev/sda5  1517920    259200   1181612  18% /
/dev/sda1    23302      8976     13123  41% /boot
/dev/sda9  2213668    553376   1547840  27% /home
/dev/sda7  1517920    736560    704252  52% /usr
/dev/sda8   806368     43432    721972   6% /var
/dev/sdb4    98078     66026     32052  68% /mnt/zip
Then, I parse through the output array to look for the size of the /var parition using the eregi_replace command.

If your pager can receive text messages, there are generally two ways of sending a message to it. Some pagers have actual email addresses, so you can send messages to them using the mail function. My pager only recieves messages sent from a form on the company's website, so I submit variables to the form processing page using the fopen function.

Now the only thing left to do is set this program to run every 30 minutes. Use the crontab command at the unix prompt to schedule this script to run automatically. The entry in my cron file looks something like this...

   0,30 * * * * php /path/to/monitor_disk_space.php
All in all, it's pretty simple and rudimentary, but it works for me. Your mileage might vary.