Study Guide: 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:

<?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

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

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:

   print('ARGC = ' . $argc ."\n\n");
   foreach ($argv as $k=>$v) {
     print("ARGV[$k] = $v\n");
   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.)

  This article uses material from the Wikipedia page available here. It is released under the Creative Commons Attribution-Share-Alike License 3.0.



Connect with defaultLogic
What We've Done
Led Digital Marketing Efforts of Top 500 e-Retailers.
Worked with Top Brands at Leading Agencies.
Successfully Managed Over $50 million in Digital Ad Spend.
Developed Strategies and Processes that Enabled Brands to Grow During an Economic Downturn.
Taught Advanced Internet Marketing Strategies at the graduate level.

Manage research, learning and skills at Create an account using LinkedIn to manage and organize your omni-channel knowledge. is like a shopping cart for information -- helping you to save, discuss and share.

  Contact Us