Juicy lil' bytes

How to Automatically Handle PHP Arguments From Both a URL and the Command Line in the Same File

Want to pass arguments to your PHP script via URL on your web server as well as with standard command line syntax via the PHP interpreter? Have your cake and eat it too with this little gem.

I used this technique in Tweetledee. It’s useful for testing your PHP scripts in a terminal and for piping your PHP script data to other applications. Here is a snippet of the code from the Tweetledee favoritesjson.php file that demonstrates the conditional argument parsing logic:

How to Handle PHP Arguments by URL and Command LineSource File
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/*******************************************************************
*   Parameters
*    - can pass via URL to web server
*    - or as a short or long switch at the command line
********************************************************************/
// Command line parameter definitions //
if (defined('STDIN')) {
    if (isset($argv)){
      // handle your command line arguments here with getopt
    }
}
// GET request parameter definitions //
else {
  // handle your URL parameters (via GET or POST requests) here
}

STDIN is defined if the script is being run directly through the PHP interpreter with a shell command, but it is not defined when you access the file through a web server by URL. Test to determine if it is defined and, if so, you can parse the PHP command line arguments with the PHP getopt function. This allows you to pass arguments using standard short (-s) and long (--long) command line switch syntax.

If the test fails, then the user is accessing the file by URL. Handle your GET and POST requests in the else code block.

Check out the full source file if you’d like to see how I handled the arguments in these conditional statements.