TalkPHP
 
 
Account Login
Latest Articles
» The basic usage of PHPTAL, a XML/XHTML template library for PHP
» Vulnerable methods and the areas they are commonly trusted in.
» Simple way to protect a form from bot
» The Basics On: How Session Stealing Works
» How to keep your forms from double posting data
IRC Channel
IRC Speech Bubble Join the friendly bunch on IRC...
(#TalkPHP on Freenode)

...Also available via a web interface.

See this thread for information on the TalkPHP Free Hugs Initiative™. Subject to availability.
Associates
Associates
CSS Tutorials
Advertisement
Introducing the PHP Command Line Interface
   PHP CLI Basics

Introduction

In this short article I will introduce you to the PHP Command Line Interface (or CLI for short). PHP CLI allows you to run PHP scripts directly from the command line bypassing the need for a web server.

Note: This article assumes that you are using PHP v4.3.0 or higher.

Why is it useful?

The PHP CLI can be useful for writing scripts that you want to run in the background or via cronjobs such as backups, pruning log files or running programs. PHP CLI scripts are also useful for testing small chunks of code without having to upload it to your web server first.

Handling Input and Output

In most scripts you will want to get some input from the user such as asking them to select an option and send some output back to them such as displaying the results

Outputting information to the screen is essentially the same as when using a web server. Using echo and print are the recommended ways to send output.

PHP Code:
<?php
 
echo "Look!  I'm some output!\n";
print 
'So am I!';
This will result in:

Code:
Look!  I'm some output!
So am I!
There are two important differences between using PHP on the command line and using PHP in a web browser to note in the above script. The first is that we don't use <br /> as we normally would to make a new line. Instead we use the new line character \n. The second difference is that when using the new line character \n, you must enclose the string in double-quotes. Like variables, PHP won't parse the \n if it is enclosed in single-quotes, it will just echo it as normal text.

As with most scripts, you will eventually wish to get some input from the user. The PHP CLI provides a few ways to do this. The most common is to use the fgets() function. fgets() will read everything the user types until they press Enter.

PHP Code:
<?php
 
echo 'Please enter your first name: ';
$firstName fgets(STDIN);
 
echo 
'Hello ' $firstName;
As you can see in the above script, it asks the user to enter their name. fgets() then waits for the user to press Enter, then puts their input into the $firstName variable. We then use this in our personal greeting.

Note: STDIN and STDERR

STDIN and STDOUT are special streams provided by PHP for Input and Output. STDIN (STandarD INput) will contain all input from the user and STDOUT (STandarD OUTput) will contain all output that gets sent to the user.

So using fgets(STDIN) means that we want to fetch input from the Standard Input stream using the fgets() function.

There are many other functions for fetching user input such as fgetc and sscanf which are worth investigating further


Parsing parameters / arguments to your CLI script

You will frequently find yourself needing to parse command line arguments to your CLI scripts.

In a web-based application you would typically do this by adding them to the URL:

http://www.example.com/myscript.php?...something=else

This would result in the following variables becoming available in your PHP script:

PHP Code:
$_GET['this'// Contains "that"
$_GET['something'// Contains "else" 
Arguments are handled slightly differently in a PHP CLI script. To pass arguments in your CLI script you would do the following:

Code:
php myscript.php something else
This would pass the values "something" and "else" to your PHP script.

To use these within your script you need to take advantage of the $_SERVER superglobal array. Specifically, $_SERVER['argc'] and $_SERVER['argv'].

$_SERVER['argc'] (argument count) contains the number of arguments passed to your script. It's important to note that this number includes the name of the script itself.

For example, if your script contained the following:

PHP Code:
<?php
 
echo $_SERVER['argc'];
And you ran it with the following arguments:

Code:
php myscript.php Alan Wagstaff TalkPHP
Your script would output 4. The arguments it counts are "myscript.php", "Alan", "Wagstaff" and "TalkPHP".

If we modify our script to use $_SERVER['argv'] (argument values) to print a list of the arguments we pass we can see this in action:

PHP Code:
<?php
 
print_r
($_SERVER['argv'];
If you now run the script with the following arguments:

Code:
php myscript.php Alan Wagstaff TalkPHP
It should output something similar to:

Code:
Array
(
    [0] => e:\webroot\talkphp\cli_basics\myscript.php
    [1] => Alan
    [2] => Wagstaff
    [3] => TalkPHP
)
As such, it's important to remember that when accessing your arguments in PHP CLI scripts, you need to start with $_SERVER['argv'][1] to get your first argument.


Conclusion

Hopefully this has given you an introduction to the basics of writing command line applications using PHP. For further reading on the PHP CLI, check out the links below.


Further Reading

PHP: Using PHP from the command line - Manual
PHP CLI
Report this Article
Last 5 Article Reviews Read All Reviews
   Zend Framework CLI
Review added by JaoudeStudios on 07-15-2009
Zend framework does this very well, it probably was not around when you wrote this article.

http://framework.zend.com/manual/en/zend.console.getopt.html
   Good article
Review added by sketchMedia on 05-31-2008
Good little article this, it really displays the power of PHP. Although i think you should have included some information on the 'shebang' and running PHP files as an executable.

Great job all the same.
   Great introduction
Review added by Wildhoney on 01-11-2008
A great introduction there to CLI, Alan. Thanks a lot for sharing! I'm sure there's many people out there who are not aware PHP can be run via a CLI.
   .....
Review added by danielneri on 01-11-2008

All times are GMT. The time now is 10:05 AM.

 
     

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0
Inactive Reminders By Icora Web Design