Give feedback to your users (PHP CLI coding)

Posted on July 17, 2011
by

Terminal PHP CLI

Whereas PHP’s main usage is to generate web pages, it can also be used as a scripting language in your shell (just like bash or python). To that purpose, you can use the CLI version of PHP (CLI standing for Command Line Interface).

The purpose of a CLI script is different, it’s not to generate a web page. Instead, it can be an automatisation task for your website or a maintenance task for your server. Therefore, of course, when you write a CLI script, you don’t output HTML, but instead you output short messages that will tell the user if the script went well or not.

This script can be run manually by you or a coworker, or a cron job can run it periodically. In all the cases, giving a feedback about the success or failure of your script is important. It’s not difficult, simply print a message and append a new line character to it (\n, not the HTML breaking line tag <br/>). I find my custom (and very simple) function println() (yes, inspired from Java :)) quite convenient for this. See code below:
<?php
/**
* Prints a string and appends a new line to it
*
* @param string $t
*/
function println($t = '') {
echo $t . "\n";
}
 
// start script
println('Script starting');
 
// instantiate new database object
$db = new Db();
 
// die if unable to connect to database
if (!$db->connect()) {
println('Not able to connect to database');
die();
 
// print success message if connection successful
} else {
println('Connection to database successful');
}
 
// execute query
$db->query(
'UPDATE
tablename
SET
date = NOW()'
);
 
// if no error occured, print success message
if ($db->getError() === null) {
println('Date updated');
 
// if error occured, print error
} else {
println('An SQL error occured: ' . $db->getError());
die();
}
 
// end script
println('End of script');

To run your script, simply enter the following command in your shell:

php cli.php

And here is what it looks like in my console:

PHP CLI feedback

Quite a good explanation feedback. Oops, I think I have to check out my database now… 😮

Tip: when your CLI script (PHP or not) are run automatically (let’s take the example of a cron job), it’s good to redirect the output to a file. It will constitute a log file that you can always check later to see how the script went while you were away. In your crontab file, it works like this:

* * * * * cd /Users/cyril/Sites/ && php cli.php >> /var/log/php-cli/cli.log 2>&1

This will run your script every minute and append the output of your script to the file /var/log/php-cli/cli.log, file that you can always check at any time to see if your scripts were correctly run.

About the author

Cyril Mazur is a serial web entrepreneur with experience in various fields: online dating, forex & finance, blogging, online advertising... who enjoys building things that people like to use.

Leave the first comment