·

photo credit: Marithe^Franzy via photopin cc

PHP as a CLI language

Some of you might already know this, but I use PHP as a CLI language quite often. And why not?

  • It’s PHP, the language I know best.
  • It has access to the file system so you can do all kind of magic with it.
  • Like any shell script it’s great for maintenance, scaffolding or periodic tasks.
  • They can easily be implemented in any workflow.

So how can you utilize PHP as CLI the best? I’ll try to show you how …

It’s just PHP

If you can program PHP, you can also utilize it for shell scripting. Just create a PHP script, and execute it from the terminal with the php  command:

Congratulations! You’ve just ran a PHP script from the terminal.

Make it a shell script

We can even make the file itself an executable by adding a hashbang to the first line and make the file executabel (chmod +x ):

We can now execute this file from the shell like so:

The differences

There are some differences however, the biggest ones are:

  • Certain variables are not available or different
    Take $_SERVER  for example. If you compare this variable with the same one when running on a webserver, you’ll notice quite a difference in keys. Other scopes, like $_GET , $_POST , $_REQUEST , $_COOKIE  or $_SESSION  are not available at all.
  • It’s run as a different user
    This could cause issues when trying to edit files that are also edited by the webserver user.
  • No html markup in errors This is a php.ini setting(html_errors), but this defaults to off in the cli version.
  • Logging to stderr Usually errors are logged to the webservers error.log, but in the cli version errors are written to stderr. This is also available as a php.ini setting(error_log)
  • php.ini The php.ini file that is used for the cli version can be a different file. Which can lead to some nasty bugs (curl suddenly not available, etc).
  • Different executables It’s possible to install multiple version of php (php5 alongside php4). Use which php  to determine which version you’re using.
  • Everything is shown as text var_dump() is readable without a <pre> ,No difference between header(‘Hello’)  and echo(‘Hello’)

Secure it

Now, before we go any further it’s good to take notice that it’s good practice to prevent your PHP CLI script to be executable from a browser. After all, you might use PHP CLI for maintenance tasks, or monitoring and you don’t want any nasty results because some script kiddy is executing your PHP CLI scripts. Therefore it’s good prevent your PHP CLI script from being executed by a browser. This can be easily done with php_sapi_name() :

On the next page I’ll explain how to deal with arguments in a PHP CLI script.

Leave a Reply