Simple WebCron support for PHP Server Monitor

Needing to monitor the status of a Webserver for multiple users without much of a hassle I installed the PHP Server Monitor on my shared hosting solution and set it up to monitor the status of the webpage. Without the ability to to set up a cronjob, however, the status updates would still need to be done manually on the server monitor page, rendering the whole project useless. The standard script to update server status can only be run from commandline, so i made a few modifications to be able to run it using a simple webcron service (https://cron-job.org).

<?php 
// include main configuration and functionality 
require_once dirname(__FILE__) . '/../src/bootstrap.php'; 
$cron_timeout = PSM_CRON_TIMEOUT; 
if( $_GET['token'] == 'someMD5hashorwhatever' ) {
    $time = time();
    if( psm_get_conf('cron_running') == 1 && $cron_timeout > 0 && ($time - psm_get_conf('cron_running_time') < $cron_timeout) ) {
        die('Cron is already running. Exiting.');
    }
    if(!defined('PSM_DEBUG') || !PSM_DEBUG) {
        psm_update_conf('cron_running', 1);
    }
    psm_update_conf('cron_running_time', $time);
    $autorun = new \psm\Util\Server\UpdateManager($db);
    $autorun->run();
    psm_update_conf('cron_running', 0);
    echo("Serverstatus successfully updated.");
    } else {
        throw new Exception("Wrong token.");
    }

Basically I threw out the commandline specifics and included a simple condition that checks if a (currently hardcoded) token is passed with the call to the script, leaving everything else in place to avoid breaking anything. Once the update is successful a result is returned and an exception resulting in a 500 internal server error is thrown if a wrong token is passed. This allows the webcron to monitor success of the tasks.

Calling http://phpservermonitor/cron/webcronstatus.php every x minutes from the webcron service will now update the status of all servers without the need to install a local cron job or systemd timer.

Leave a Reply

Your email address will not be published.