PHP Articles
Basic & Beginners
Advanced
Database
XML, Webservices
Design Patterns
Ajax
All Articles
Main Menu
Home
About PHP Hacks
Links
Contact Us
Search


Shell Scripting with PHP CLI PDF Print E-mail
Friday, 28 July 2006
As most of us already know, PHP is the best language for developing dynamic web pages available today. Not many people are aware that it can be used as a shell scripting language as well. While PHP as a shell script isn't as robust as Bash or Perl it does have definite advantages, especially if you're like me and are more proficient in PHP than you are in Perl.

The requirements for using PHP as a shell language is that you must compile PHP as a CGI binary instead of as an Apache module. There are certain security issues related to this so please refer to the PHP Manual when doing so.

Where the code is concerned, the only difference between a PHP shell script and a regular PHP web page is the existence of the standard shell call at the top of the script:

#!/usr/local/bin/php –q

We're using the '-q' switch so that the HTTP headers are suppressed. Also, you're still required to begin and end the script with the standard PHP tags:

<?php ?>

So let's delve into the standard code sample:

#!/usr/local/bin/php -q
<?php
 
    print("Hello, world!\n");
 
?>

This, as most of you know, will simply output to the screen "Hello, world!".

Passing arguments to the shell script

Commonly with a shell script you need to pass arguments to the script. This is easily done using the built-in '$argv' array as show in the following example:

#!/usr/local/bin/php -q
<?php
 
    $first_name = $argv[1];
    $last_name = $argv[2];
 
    print("Hello, $first_name $last_name!  How are you today?\n");
 
?>

So in the above script we're printing out the first two arguments to the script, which would be called like this:

[root@pd root]$ scriptname.ph Jim Baker

Which would print out:

Hello, Jim Baker!  How are you today?
[root@pd root]$

The only major difference with the '$argv' array between a shell script and a web page is that in a shell script, '$argv[0]' is the name of your script. In a web page it is the first argument in your query string.

Making a script more interactive

But how do we wait for user input? How do we create a truly interactive script? Well, PHP has no native functions like the 'read' command in shell but we can always emulate it using the following PHP function:

*Note that this function will only work for Unix.

<?php
 
function read() {
    $fp=fopen("/dev/stdin", "r");
    $input=fgets($fp, 255);
    fclose($fp);
    return $input;
}
 
?>

This function opens a file pointer to Standard In (/dev/stdin on Linux) and reads anything from this pointer up to 255 bytes, newline, or EOF. In this case a newline is most likely to occur. It then closes the file pointer and returns the data.

So now let's modify our previous script to wait for user input using the newly created 'read()' function:

#!/usr/local/bin/php -q
<?php
 
    function read() {
        $fp=fopen("/dev/stdin", "r");
        $input=fgets($fp, 255);
        fclose($fp);
        return $input;
    }
 
    print("What is your first name? ");
    $first_name = read();
    print("What is your last name? ");
    $last_name = read();
    print("\nHello, $first_name $last_name!  Nice to meet you!\n");
 
?>

You may notice, however, that when you execute this script the last line to be printed is broken into three lines instead of one, as it should be. This is because our 'read()' function also takes in the newline character. This is easily fixed by stripping off the newline before we return the data:

<?php
 
function read() {
    $fp=fopen("/dev/stdin", "r");
    $input=fgets($fp, 255);
    fclose($fp);
    return str_replace("\n", "", $input);
}
 
?>

Embedding PHP shell scripts within a regular shell script

Sometimes it might be handy to embed a PHP shell script within a script written in Bash or other shell. This is fairly simple but can get a bit tricky.

First, lets embed the PHP code:

#!/bin/bash
echo This is the Bash section of the code.
 
/usr/local/bin/php -q << EOF
 
<?php
 
    print("This is the PHP section of the code\n");
 
?>
 
EOF

Pretty simple huh? Until you add a variable that is. This is the tricky part. Try running the following code segment:

#!/bin/bash
echo This is the Bash section of the code.
 
/usr/local/bin/php -q << EOF
 
<?php
 
    $myVar = "PHP";
    print("This is the $myVar section of the code.\n");
 
?>
 
EOF

You'll get the following error:

<b>Parse error</b>: parse error in <b>-</b> on line <b>2</b><br>

To fix this you have to escape all of the '$' characters in your PHP code:

#!/bin/bash
echo This is the Bash section of the code.
 
/usr/local/bin/php -q << EOF
 
<?php
 
    $myVar = "PHP";
    print("This is the \$myVar section of the code.\n");
 
?>
 
EOF

That should get you started on creating your own shell scripts using PHP!

Comments
Add NewSearchRSS
uzla IP:212.159.0.6 | 2006-09-25 17:08:54
Very good article. If you want to know more, please. have a look at PHP CLI dedicated web site at http://www.php-cli.com . There is everying there!
Barry D. IP:68.148.138.209 | 2006-11-22 18:14:21
I wouldn't reconmend www.php-cli.com it only consists of a few pages, and they are mostly links to other pages.

1 of the issues with PHP-CLI, most of the stdin halts the script, waits for user input, where most programmers want the script to continue processing say a loop, and listen for user input. A great challenge for this you can find at http://groups-beta.google.com/group/PHP-Hacks?hl=en

At the bottom is a project called phpMini, and it runs completly in php-cli, on any system, however, there is class called command that uses a linux system command clear, if you wish to clear the screen in windows, use cls.
rick - a qustion IP:84.172.239.227 | 2006-10-26 15:25:46


Definitely here it is PHP of version CGI. Can I run the script 'test.php' through the functin 'system() or exec()'? It will succeed or fail???
rick - i meant... IP:84.172.239.227 | 2006-10-26 15:34:13
i.e.
// the code in the test.php
system("/path_to_php/php test.php");

Can I run the script 'test.php' through the function 'system() or exec()'? It will succeed or fail???
Barry D. IP:68.148.138.209 | 2006-11-22 18:19:18
You have to first chmod +x 'php test.php' for it to be executed by the system first, especially in linux, however, in windows, you would have to associate the php file with a php preprocessor, which must be installed manually from the website, http://php.net/downloads.php
rick - I think... IP:84.172.239.227 | 2006-10-26 15:38:12
system("/path_to_php/php test.php"); dosn't work, unless it is a CLI-PHP, it has to be a PHP of version CLI. Am i right???
rick - I got answer IP:84.172.211.109 | 2006-10-27 08:18:55
'/path_to_php/php test.php' has to be written in a shell-script 'test.sh', then run the function 'shell_exec(sh test.sh);' in a php-file.

Thanks, thanks myself!!! It has nothing to do with CGI-PHP or CLI-PHP.
try - yrty IP:217.155.215.22 | 2007-02-22 16:43:49
rtyrtytry
try - ewr IP:217.155.215.22 | 2007-02-22 16:44:17
wer
Travis Tidwell - PHP Command Line Utility IP:63.230.62.80 | 2007-05-04 06:01:00
I just created a new utility that makes creating these scripts much easier. You can check it out at http://www.travistidwell.com/node/86. The utility is a free download.

Let me know what you think.
Only registered users can write comments!
Last Updated ( Wednesday, 09 August 2006 )
 
< Prev   Next >

Syndicate


Login Form





Lost Password?
No account yet? Register