Shell Scripting with PHP in the command-line interpreter (CLI) environment.

Category: Software and Systems Engineering
Author: Sean O'Donnell
Thu, Feb. 20th, 2003 @ 2:20:22 (MST)

This example demonstrates the use of PHP in the command-line interpreter (CLI) environment, rather than the traditional HTTP environment.


#!/usr/bin/env php
"hello world!\n";

You can save the code above to a file named "helloworld.php", and then execute the following command:

 $ chmod +x ./helloworld.php;
$ ./helloworld.php

The following results should be displayed to your terminal:

 hello world! 

PHP is a very under-rated/dis-respected scripting language, when it comes to linux/unix shell scripting.

However, the API extensions that are built-in, along with the lack of data type and memory management requirements (that make some developers cringe), make it a very formidable language to common shell scripting languages, such as bash, perl, python, and ruby. While I don't like flame-wars over languages, I do prefer PHP, mostly as an old/bad-habit. ;-p

Accessing Environment Variables via PHP/CLI

In PHP, there are (2) basic ways to access Environment Variables.

  1. Super Global Variables ($_SERVER)
  2. The getenv() Method

Personally, these days, I prefer the getenv() method. I don't trust super-global variables to still exist in the upcoming releases of PHP, since they fundamentally represent basic security problems, and have been re-factored a few times over the past few releases.


$home = getenv('HOME');
print "My Home Directory is: ". $home;

The script above would print your cli environment $HOME directory path, via PHP.

Copyleft (<) 1998-2019