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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
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.