PHP Programming/PHP CLI

Contrary to popular belief, PHP is not just a web server language. PHP can also be used to create regular programs. PHP can be used to create GUI applications, shell scripts, and even daemons, among other things.

The boon is that all (or most) of the usual PHP libraries are available to your PHP CLI program too. MySQL, XML, etc. It's all (or mostly) still available.

Example PHP-CLI Program
Below is an example PHP-CLI program:



If we saved this as "helloworld.php", then we'd run this PHP CLI program via the command: php helloworld.php

This would produce the output: Hello World

Difference Between PHP and PHP CLI
There are some important differences between server-side PHP and PHP CLI. Here's a list of them:
 * 1) There is no   super global array.
 * 2) There is no   super global array.
 * 3) There is no   super global array.
 * 4) When you do a print, the output goes to the standard output and not a web browser.
 * 5) You can get command line arguments via the   variable.
 * 6) You can get the number of command line arguments via the   variable.

Using and
Like many programs, it is necessary to access the command line variable used to invoke the program. To do this in PHP we have two variables:

With  in the php.ini file one can use:

With  in the php.ini file one can use:

(For those know Bash, C or C++ program languages. they'll find these pair of variables to be very familiar)

Below is an program that makes use of the  and   variables:

If we save this PHP program as "test1.php", and ran it with: php test1.php apple orange banana pineapple Then we'd get: ARGC = 5 ARGV[0] = test1.php ARGV[1] = apple ARGV[2] = orange ARGV[3] = banana ARGV[4] = pineapple

(Note that like in Bash, C and C++ programs, the first element of  is the name of the program.)