In a previous post we discussed how to tell whether or not you are on the command-line from within your PHP script. Today we’re going to talk about passing command-line arguments to your script. When on the command-line two variables are available to you,
$argv. They are the argument count and argument vector, the former contains the number of arguments and the latter an array of the arguments. The name of the script is always present, so even when no arguments are passed in the count will be 1 and the array will contain the name of your script.
The following is a basic “Hello World” script (we’ll call it
hello.php that takes the name from an argument and throws an error if no name is specified:
Now if the person running the script decides to specify more than a single name or no name at all they will be met with an error that contains usage instructions (like most command-line apps do). If they run the command correctly as
php -f hello.php Josh they will be greeted with a very enthusiastic hello!