Using PHP as a shell scripting language

As most of us already know, PHP is one of the most popular scripting language for developing dynamic web pages. But you probably don’t know that PHP can be used as a shell scripting language. It isn’t robust as Bash or Perl but it has some advantages.

The only difference between a PHP shell script and a regular PHP file which serves web page is the first line:

#!/usr/bin/php -q

The ‘-q’ switch is here to suppress the HTTP headers. After the first line, you just add standard PHP tags:

<?php ?>

Here is the example so you can see what I’m talking about:

#!/usr/bin/php -q
<?php
 
    print("Hi there folks !\n");
 
?>

Save these lines as test.php and execute with:

# php test.php

Good idea is to add the next lines at the beginning:

if (!isset($_SERVER["argv"][0]) || isset($_SERVER['REQUEST_METHOD'])  || isset($_SERVER['REMOTE_ADDR'])) {
	die ("<br><strong>Shell access only</strong>");
}

In this case, this script can be accessible via browser but those lines will kill the script in case if it is issued via browser.

Leave a Reply

Your email address will not be published. Required fields are marked *