Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Library to get command line options and parameters

Is there a PHP library that I can use to parse options and parameters in a command line php script? I do know the function getopt, but is there something similar for parameters?

like image 912
Donovan Avatar asked Mar 16 '12 11:03

Donovan


People also ask

Can we use PHP for command line scripts?

There are two variables you can use while writing command line applications with PHP: $argc and $argv. The first is the number of arguments plus one (the name of the script running). The second is an array containing the arguments, starting with the script name as number zero ($argv[0]).

What is $argv in PHP?

$argv — Array of arguments passed to script.

How do I pass a command line argument in PHP?

To pass command line arguments to the script, we simply put them right after the script name like so... Note that the 0th argument is the name of the PHP script that is run. The rest of the array are the values passed in on the command line. The values are accessed via the $argv array.


2 Answers

getopt is a possibility but it's no fun, especially not if you're used to Python (or Ruby, which probably has similarly beautiful argv parsers). Here are some better alternatives, they probably all require PHP 5.3+.

  • I've tried Commando and I'm happy with it.

  • ConsoleKit would have been next in line.

  • php-cli-tools has some more functionality such as progress indicators and tabular displays. I only found it 10 minutes ago, since I want tabular display I might move to this library from Commando at some point.

  • Also check GetOptionKit as it can handle subcommands.

like image 127
kqw Avatar answered Sep 21 '22 12:09

kqw


Use getopt for options and the $argv array for parameters - http://php.net/manual/en/reserved.variables.argv.php

also have a look at http://docs.php.net/manual/en/features.commandline.php for stuff like reading arguments from $argv of the form --name=VALUE

like image 24
scibuff Avatar answered Sep 18 '22 12:09

scibuff