Skip to content
Advertisement

Email notification when disk drive reaches a certain percentage? (Laravel)

I’d love to be able to monitor my disk drives automatically with email notifications. I’m using Laravel (and therefore it should be possible to schedule a task to check) this but I’m unsure how to go about checking the available disk size through Laravel/PHP code. Any ideas?

I did find this article (but it’s not strictly what I want as it uses shell directly to send emails and I want a laravel scheduled task to send the emails whenever it finds the disk drive at a specified percentage): https://www.cyberciti.biz/tips/shell-script-to-watch-the-disk-space.html

Advertisement

Answer

One good way I would do this is, at first, prepare a function to check for disk space.

function spaceLimit($limitPercent) {
    $drive = "/";
    $space = (disk_free_space($drive) / disk_total_space($drive)) * 100;
    return $limitPercent < $space;
}

Then, send an email after checking at a specific internal (in file app/Console/Kernel.php).

protected function schedule(Schedule $schedule)
{
    // Ensure queue:work is running
    $schedule->call(function() {
        // 90% and more space used
        if (spaceLimit(90)) {
            Mail::to('admin@me.com')->send(/* Some Mailable Class here */);
        }
    })->everyFiveMinutes(); // Change interval here
}

Of course, the spaceLimit function can be stored in the same file, or in another, or wherever you want.
Also, you can imagine having an Event class to easily handle other kinds of notifications later (such as SMS, Push Notification, whatever..).

Don’t forget you will need to configure a cron to execute your tasks. Crontab :

* * * * * cd /var/www/html && php artisan schedule:run >> /dev/null 2>&1

And, if your emails are in a queue, you will also need to start the queue :

php artisan queue:listen
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement