Created
April 6, 2013 15:45
-
-
Save dmolsen/5326548 to your computer and use it in GitHub Desktop.
A very simple example of setting up a command line tool using PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* A ridiculously simple example of using PHP as a command line tool | |
* | |
* The following usage is supported by this script: | |
* | |
* php cli.php -a [-c] | |
* Do something based on the -a flag. Use the optional -c flag to modify what happens when using the -a flag. | |
* | |
* php cli.php -b foo | |
* Do something because the -b flag is set to 'foo'. | |
* | |
* php cli.php -b bar | |
* Do something because the -b flag is set to 'bar'. | |
* | |
* php cli.php | |
* Write out the default usage information. | |
*/ | |
// make sure this script is being accessed from the command line | |
if (php_sapi_name() == 'cli') { | |
/* | |
* Define the supported flags | |
* single letters (e.g. a & c) act as boolean (true/false) operators | |
* letters with colons (e.g. b) act as string passing whatever text immediately follows the flag | |
*/ | |
$args = getopt("ab:c"); | |
if (isset($args["a"])) { | |
// check to see if the -c flag is set. this makes -c an optional argument for the -a flag | |
$option = false; | |
if (isset($args["c"])) { | |
$option = true; | |
} | |
$include = $option ? "was used" : "wasn't used"; | |
// do something based on the -a flag | |
print "\n"; | |
print "You used the -a flag and the -c flag ".$include.".\n\n"; | |
} elseif (isset($args["b"]) && ($args["b"] == "foo")) { | |
// do something based on the -b flag being set to the string 'foo' | |
print "\n"; | |
print "You used the -b flag and the value 'foo'.\n\n"; | |
} elseif (isset($args["b"]) && ($args["b"] == "bar")) { | |
// do something based on the -b flag being set to the string 'bar' | |
print "\n"; | |
print "You used the -b flag and the value 'bar'.\n\n"; | |
} elseif (isset($args["b"])) { | |
// catching an error | |
print "\n"; | |
print "You used the -b flag and supplied a value but it was neither 'foo' nor 'bar'. Please use one of those two values.\n\n"; | |
} else { | |
// when in doubt write out the usage | |
print "\n"; | |
print "Usage:\n\n"; | |
print " php cli.php -a [-c]\n"; | |
print " Do something. Use the optional -c flag to modify what happens when using the -a flag.\n\n"; | |
print " php cli.php -b foo\n"; | |
print " Do something because the -b flag is set to 'foo'.\n\n"; | |
print " php cli.php -b bar\n"; | |
print " Do something because the -b flag is set to 'bar'.\n\n"; | |
} | |
} else { | |
print "This script should only be run from the command line."; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment