Search iEntry News

UnixProNews
SecurityProNews
ITmanagement












An Alternative To Perl: Shell Scripting With PHP

By Jayesh Jain
Expert Author
Article Date: 2003-07-16

I know that you all want to get rid of Perl Scripts because of their complexity and the fact that Perl is not an easy language to learn. With the introduction of PHP 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 application (scripts) with PHP, meaning that 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.

In this tutorial I will show you how to use PHP's CLI feature to interpret shell scripts. I will assume that you have a 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 a Linux machine).

What are PHP Shell Scripts?

Normally shells are interactive, but not always. This means that the shell accepts commands from you through your keyboard and executes them. But instead of issuing command one by one, we can store this sequence of commands in a text file and tell PHP to execute this text file instead of entering the commands manually. This is known as PHP shell scripting.

PHP shell scripts are just like batch files in MS-DOS, but they have more power than the MS-DOS batch file, thanks to PHP.

Why Write Shell Scripts?
Here are some reasons why you may want to consider writing PHP shell scripts:
  1. Shell script can take input from a user or file and output them on screen

  2. Useful to create your own commands/applications

  3. Don't have to reinvent the wheel

  4. Can be used to automate some day to day tasks, such as backups


Getting Started
Lets start with a small script to display the typical "Hello World" text. Create a text file called world.php. Enter the following code into world.php and save it in your PHP directory:



Open your command prompt change into the folder where PHP is installed and run the following command:

php world.php



If you're surprised to see the output at the command prompt instead of in a web browser, then welcome to the other dimension of PHP! You may have noticed that the following header is also included in the output (PHP does this be 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:

  • -q (Quiet mode. Suppress HTTP Header output)

  • -w (Display source with stripped comments and white space)

  • -v (Version number)

  • -c (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)

  • -d (This option allows you to set a custom value for any of the configuration directives allowed in php.ini. The syntax is: -d configuration_directive[=value])

  • -l (This option checks the syntax in the source file)

  • -i (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, just like this:



[Note] For all you Linux fans, you can also redirect the script output to another command by using the | (pipe operator) e.g. : php world.php | sort [End Note]

There are three streams available in the PHP CLI, which are:
  1. stdin ('php://stdin')

  2. stdout ('php://stdout')

  3. stderr ('php://stderr')

This following example will display "Hello World" in the output window using the output stream:



This example will demonstrate how to use an input stream. It will accept input from the user and wait until the user presses the enter key and then it will display the text entered:



This following example shows you how to output text to an error stream:



OK, before we move ahead, there are a few things that you should know. The output to the error stream is always sent to the error device (normally screen) and is not sent to file or another command when redirecting the output. Always make sure you close this stream once you are done with it. Please refer to the PHP manual if you need more information on the 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 too. Curious? Let's take a look...

All of the arguments passed to your script are stored in a zero based global array variable called $argv. There is also another global variable, $argc, which holds number of arguments passed to the script (For all of those coming from a C/C++ background, this should be familiar to you).

One thing you need to remember is that $argc will always be one or more - never zero. This is because the name of the script being interpreted is always the first argument to the PHP interpreter. Here's the code, which will display the total number of arguments passed. It will also will display what those arguments are arguments:



Assuming this code is entered into a file called argument.php, you could test this script by running something like this:

php argument.php arg1 arg2

Here's the output:



Using PHP Script Instead of Perl Scripts
As you must have guessed so far, the PHP executable can run independently from the web server. If you want to run your PHP scripts instead of Perl scripts -- which should be transparent to the system - you need to add a shebang to the top of the PHP script that you want to execute. A shebang looks like this:



This will tell the UNIX system that it needs to run the PHP interpreter for the following script, and the good thing is that this line will be ignored when you run the script under a Windows environment, thus you can write PHP scripts that are not operating system specific:



[Note] Don't forget to add the PHP tags in the script file, otherwise 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 that we discussed earlier by specifying them after the shebang [End Note]

Configuring Windows to Executing PHP Scripts
If you plan to run PHP scripts from a command line on a Windows machine, then 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. Next, click on the file types tab and select the new button. Type .php into the file extension box and click OK:



You now need to select the PHP entry in the registered file types list box and click on the advanced button. Click new and type "Run" in the action box. In the "Application Used to Perform Actions" box, type C:PHPPHP.exe "%1" %* (change the PHP path if its different on your machine, %* is used to send any command line arguments). Click OK, and then OK again and then the close button:



With this step completed, Windows is now configured to run PHP Scripts. To try it out, just double click on any PHP file using Windows Explorer to see it running.

[Note] You can also register files with different PHP extensions, such as .php3 and .php4 using the same method mentioned above. [End Note]

Conclusion

Hopefully this article has shown you that PHP can quite easily be used for shell scripting on both Windows and Linux web servers. If you were running Perl scripts, then you now have the basic knowledge to convert them to PHP and run them from the command line.

Remember that you are not limited to basic echo statements from the command line. You can access databases from your shell scripts, send emails, creates complex applications or do whatever you would normally do in a browser-based PHP script, except output and render HTML of course.

First appeared at DevArticles. Reprinted with permission from the author.

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. Contact him at: jainjayesh74@yahoo.com



Newsletter Archive | Article Archive | Submit Article | Advertising Information | Resources | About Us | Contact

UnixProNews is an iEntry, Inc. ® publication - 1998-2008 All Rights Reserved Privacy Policy and Legal