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

edit

Below is an example PHP-CLI program:

<?php print('Hello World');  ?>

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

edit

There are some important differences between server-side PHP and PHP CLI. Here's a list of them:

  1. There is no $_GET super global array.
  2. There is no $_POST super global array.
  3. There is no $_COOKIE 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 $argv variable.
  6. You can get the number of command line arguments via the $argc variable.

Using argv and argc

edit

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 register_globals = on; in the php.ini file one can use:

  • $argv
  • $argc

With register_globals = off; in the php.ini file one can use:

  • $_SERVER['argv']
  • $_SERVER['argc']

(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 $argc and $argv variables:

 <?php 
   print('ARGC = ' . $argc ."\n\n");
   foreach ($argv as $k=>$v) {
     print("ARGV[$k] = $v\n");
   }
 ?>
 <?php 
   print('ARGC = ' . $_SERVER['argc'] ."\n\n");
   foreach ($_SERVER['argv'] as $k => $v) {
     print("ARGV[$k] = $v\n");
   }
 ?>

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 $argv is the name of the program.)