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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s