PHP countdown timer

Other
PHP countdown timer

I had to made ​​a few days ago, a php countdown timer, which runs from the command line, for educational purposes.

Script receive as input a number of seconds that converts then in days, hours, minutes, seconds, and display time. If receive another parameter t after display time it starts to countdown.

The script can be runned like this:

    php Cli.php -s 3600
    php Cli.php -s 5 -t

Here is script source code of PHP Cli file:

<?php
/**
 * A little script that transform a number of seconds given as parameter from 
 * comand line in days, hours, minutes, seconds. Also if a option t parameter
 * is given script is act as an countdown timer, displaying on each second 
 * remaning time.
 * Tested on Windows 7 platform with PHP 5.3.1
 * 
 * @author Moldovan Gheorghe Daniel <moldovan.gheorghe.daniel@gmail.com------>
 */
if (PHP_SAPI === 'cli') {
    $params = getopt('s:t::');

    /* Validating input part */
    if ($params['s'] == null) {
        echo 'Parameter s is required.';
        exit;
    }
    if (!is_numeric($params['s'])) {
        echo 'Value of s parameter must be numeric.';
        exit;
    }
    if ($params['s'] &gt; 86313600) {
        echo 'Value of s parameter need to be smaller then: 86313600';
        exit;
    }

    /* Script functiolity */
    if (isset($params['t'])) {
        //countdown timer
        while ($params['s'] >= 0) {
            echo chr(27); //to keep print on the same line
            echo sprintf("%03d days %02d hours %02d minutes %02d seconds", floor($params['s'] / 86400), gmdate('H', $params['s']), gmdate('i', $params['s']), gmdate('s', $params['s'])) . "\r";
            sleep(1);
            $params['s']--;
        }
    } else {
        echo sprintf("%03d days %02d hours %02d minutes %02d seconds", floor($params['s'] / 86400), gmdate('H', $params['s']), gmdate('i', $params['s']), gmdate('s', $params['s']));
    }

} else {
    echo 'Please run this script from comand line!';
}


Add comment
 
 
 

Comments