With the introduction of version 4.2, PHP has started supporting a new SAPI (Server Application Programming Interface) called CLI (Command Line Interface). This facility was introduced to help developers create small shell applications (scripts) with PHP. So, now you can kiss Perl goodbye forever.
The CLI SAPI was released for the first time with PHP 4.2.0, but was still experimental back then and had to be explicitly enabled with --enable-cli when running ./configure. With PHP 4.3.0 the CLI SAPI will no longer be experimental and therefore will always be built and installed as the php (called php.exe on Windows) binary.
What is PHP Shell Scripts?
Normally shells are interactive, but not always. It means the shell will accept commands from you through keyboard and execute them. But instead of issuing commands one by one we can store this sequence of commands into a text file and tell the PHP to execute this text file instead of entering the commands. This is known as PHP shell scripting.
A PHP Shell script is just like batch file is MS-DOS but has more power than the MS-DOS batch file, thanks to PHP.
Why Write Shell Scripts?
Shell scripts can take input from a user or a file and output them to the screen.
Useful to create our own commands/application.
Don't have to reinvent the wheel.
To automate some day to day tasks.
In this tutorial we shall learn how to use PHP's CLI feature to interpret shell scripts, we assume that you have fair understanding of PHP and that PHP is installed and working properly on your computer, you can have PHP installed on Linux or Windows (the examples in this tutorial are demonstrated with PHP installed under Windows but they should work the same on Linux machine)
Lets start with a small script (the most familiar one) to display "Hello World", create a text file "world.php" with the following text in your PHP folder.
echo "Hello World";
Open your command prompt and change your directory to the folder where PHP is installed and run the following command:
Surprised to see the output in the command prompt, rather than in the Web browser? Welcome to the other dimension of PHP! Also, you must have noticed that the following header is in the output (PHP does that by default, which also tells you the PHP version).
To suppress this HTTP header we could run PHP with the following command line parameter.
php -q world.php
Lets look at few of the command line options available with the PHP interpreter
(Quiet-mode,Suppress HTTP Header output.)
(Display source with stripped comments and
(With this option one can either specify a
directory where to look for php.ini or you can
specify a custom INI file directly (which does
not need to be named php.ini)
(This option allows to set a custom value for any of
the configuration directives allowed in php.ini. The
syntax is: -d configuration_directive[=value])
(This option checks for the Syntax in the source file)
(This command line option calls phpinfo() and prints
out the results.)
Using Streams in Scripts
You can redirect the output from any script to a file by running:
php world.php > outputfile
Note : All you linux fans, you can also redirect the script output to another command by using the | (pipe operator) eg : php world.php | sort
There are three streams available in PHP CLI, these are:
This example will demonstrate how to use an input stream, it will accept an input from the user, wait till user presses Enter key and then shall display the entered text.
$stdin = fopen('php://stdin', 'r');
echo "Please Enter your Name :";
$mystr = fgets($stdin,100);
echo "Your Name Is :\n";
The next example shows you how to output text to an error stream
$stderr = fopen('php://stderr', 'w');
fwrite($stderr,"There was an Error");
Ok before we move ahead there are few things we should know, the output to the error stream is always send to the error device (normally the screen) and is not sent to a file or another command when redirecting the output. Always make sure you close the stream once you are done with it. Please refer to PHP manual if you need more information on fopen, fwrite, fgets and fclose functions.
Using Arguments in Scripts
As you all know we can use arguments with PHP (remember world.php was an argument to the PHP interpreter), similarly we can use arguments in our scripts. Wondering how? Lets look at it.
All the arguments passed to your script are stored in a zero based global array variable $argv, also there is one more global variable $argc which holds number of arguments passed to the script (hey all you people coming from C/C++ background this should be familiar to you). Please note: $argc will always be one or more than one as the script name is always the first argument. Here is the code which shall display the total number of argument passed and also will display the arguments
Assuming this is stored in a file argument.php you could test this script by running something like this
php argument.php arg1 arg2
Using PHP Script Instead of Perl Script
As you must have guessed so far, PHP executables can run independently from the web server. If you want to run your PHP scripts as a replacement to Perl scripts they should be transparent to the system. At the head of the document, type #!/usr/bin/php, this will tell the unix system that it needs to run PHP interpreter for the following script - this line would be ignored when you run this script under windows environment and thus you can write scripts with do not depend upon the operating system.
// your PHP code
// goes here
Don't forget to add the PHP tags in the script file, else PHP will not interpret it properly. If you want to suppress the PHP headers use #!/usr/bin/php -q, similarly you can also use any other PHP arguments
Configuring Windows to Executing PHP Scripts
For running PHP scripts on the windows machine you need to associate the PHP files with the PHP interpreter to do this Open Windows Explorer, click on the tools menu and select folder options, click in File Types tab and select new button, type .php in the file extension, click OK.
Now select the PHP entry in Registered File Types list box, click Advanced button, then new, type Run in Action box. In the Application Used to Perform Actions box type C:\PHP\PHP.exe "%1" %* (change the PHP path if its different on your machine, %* is used to send any command line arguments), Click OK, OK again and then Close button, with this windows is now configured to run PHP Scripts. Just double click on any PHP file in Windows Explorer to see it running.
Note : You can also register files with extension (.php3), (.php4) or whatever in the same fashion mentioned above.
In this article we have tried to show you the power of PHP in Shell Scripting. I am sure you must be convinced by now how flexible PHP is, also now you could use PHP instead of Perl Scripts without having to learn Perl.
Now you could access database from your Shell Scripts, send emails, creates complex applications or do whatever you could do in PHP. There is a tremendous scope to use PHP scripts and maybe someday PHP Scripts will replace Perl Scripts.
About the Author
Jayesh Jain is working as applications consultant for a health company in Auckland, New Zealand. He has several years of n-Tier development experience and is currently working with Visual Basic.NET to develop interactive client solutions. He has a passion for Web development and in the spare time he likes to write articles.