First Steps: PHP for a command line tool

I finally tasted SSH! Whats so great about it you ask? SSH allows you to access your server’s command line and edit files fast with some editors like vi. But also it lets you execute PHP files. Those PHP can then even behave like a command line tool, including input. But how could I lock a browser out and only allow access via Terminal?

At first sight this might not seem too spectacular. PHP can already handle GET and POST variables. But PHP also supports input via command line just like a C application.

fscanf(STDIN, "%d\n", $number);

I wanted to know how to make PHP identify the caller of the script. I wanted it to recognize, if it was called via a browser or via a terminal. Well it turned out is was digging my hole to the treasure right beneath the chest. The $_SERVER array shows some special keys when called via terminal. One of those is SHELL.

if (!isset($_SERVER["SHELL"])) exit("This script must be called via terminal.");

This little line of code solves the problem. Check out more info about I/O Streams. So why was I digging the wrong hole? Because the SHELL-Key is not documented at all but some other user found out and posted it in the comments.

Leave a Reply