getopt() - php 选项信息函数
getopt()
(PHP 4 >= 4.3.0, PHP 5, PHP 7)
从命令行参数列表中获取选项
说明
getopt(string $options[,array $longopts[,int &$optind]]): array解析传入脚本的选项。
参数
$options该字符串中的每个字符会被当做选项字符,匹配传入脚本的选项以单个连字符(-)开头。比如,一个选项字符串"x"识别了一个选项-x。只允许 a-z、A-Z 和 0-9。$longopts选项数组。此数组中的每个元素会被作为选项字符串,匹配了以两个连字符(--)传入到脚本的选项。例如,长选项元素"opt"识别了一个选项--opt。$optindIf the$optindparameter is present, then the index where argument parsing stopped will be written to this variable.$options可能包含了以下元素:
- 单独的字符(不接受值)
- 后面跟随冒号的字符(此选项需要值)
- 后面跟随两个冒号的字符(此选项的值可选)
Note:
$options和$longopts的格式几乎是一样的,唯一的不同之处是$longopts需要是选项的数组(每个元素为一个选项),而$options需要一个字符串(每个字符是个选项)。
返回值
此函数会返回选项/参数对,或者在失败时返回FALSE
。
选项的解析会终止于找到的第一个非选项,之后的任何东西都会被丢弃。
更新日志
版本 | 说明 |
---|---|
7.1.0 | 添加$optind参数。 |
5.3.0 | 支持"="作为参数和值的分隔符。 |
5.3.0 | 增加了可选值的支持(用"::"指定)。 |
5.3.0 | 参数$longopts在所有系统平台上均可用。 |
5.3.0 | 此函数不再依赖于操作系统,现在也能够在 Windows 上运行。 |
范例
Example #1getopt()例子:基本用法
shell> php example.php -fvalue -h
以上例程会输出:
array(2) { ["f"]=> string(5) "value" ["h"]=> bool(false) }
Example #2getopt()例子:引入长选项
shell> php example.php -f "value for f" -v -a --required value --optional="optional value" --option
以上例程会输出:
array(6) { ["f"]=> string(11) "value for f" ["v"]=> bool(false) ["a"]=> bool(false) ["required"]=> string(5) "value" ["optional"]=> string(14) "optional value" ["option"]=> bool(false) }
Example #3getopt()例子:传递同一多个选项
shell> php example.php -aaac
以上例程会输出:
array(2) { ["a"]=> array(3) { [0]=> bool(false) [1]=> bool(false) [2]=> bool(false) } ["c"]=> bool(false) }
Example #4getopt()例子:使用$optind
$ opt.php -f a b c Array ( [f] => a ) $ opt.php -f 'a b c' Array ( [f] => a b c ) $ opt.php -f "a b c" Array ( [f] => a b c ) $ opt.php -f a\ b\ c Array ( [f] => a b c ) $
Sometimes you will want to run a script from both the command line and as a web page, for example to debug with better output or a command line version that writes an image to the system but a web version that prints the image in the browser. You can use this function to get the same options whether passed as command line arguments or as $_REQUEST values. Example
Be sure to wrap your head around this PHP jewel that took me a while to comprehend: The returned array will contain a boolean FALSE for options that HAVE been specified. Because why use TRUE to indicate "yes, it's there" when you can also use FALSE for that purpose, right? This is completely counter-intuitive and is most certainly only ever possible in PHP-land.
getopt() only returns the options specified if they were listed in the options. So you cant make a switch() use default: to complain of an unknown option. :(
To elaborate on what 'ch1902' said, there certainly are instances where you may need to execute a script via CLI and the HTTP protocol. In such an instance, you can normalize how your script parses via CLI (using getopt()) as well as via HTTP (using $_GET) with the following simplified code: The above code would yield the results below when access via CLI and HTTP. /** * params = foo/bar * username = housni.yakoob */ // CLI $ php script.php --params=foo/bar --username=housni.yakoob Array ( [params] => foo/bar [username] => housni.yakoob [os] => [env] => ) // HTTP script.php?params=foo/bar&username=housni.yakoob Array ( [params] => foo/bar [username] => housni.yakoob [os] => [env] => ) /** * params = foo/bar * username = Not provided, therefore, the default value will be used. */ // CLI $ whoami && php script.php --params=foo/bar housni // foo/bar [os] => [username] => housni [env] => ) // HTTP script.php?params=foo/bar Array ( [params] => foo/bar [os] => // The username of my Apache user, the result of posix_getpwuid(posix_geteuid())['name'] [username] => www-data [env] => ) As you can see, the output is consistent when the script is executed via the CLI or the web.
One thing of important note would be that getopt() actually respects the '--' option to end an option list. Thus given the code: test.php: And running: # ./test.php ./run_vfs -h test1 -g test2 -m test3 -- this is a test -m green Will return: Array ( [h] => test1 [g] => test2 [m] => test3 ) Whereas running: # /test.php ./run_vfs -h test1 -g test2 -m test3 this is a test -m green Will return: Array ( [h] => test1 [g] => test2 [m] => Array ( [0] => test3 [1] => green ) )
Although very interesting, koenbollen at gnospamail dot com's update of the argv array fails when option values follow the option with no space : Indeed php MyScript.php5 -t5 and php MyScript.php5 -t 5 with $options="t:" are treated as the same by getopt. This upgraded function should take care of it : File : shift_test.php5 >php shift_test.php5 -h -t4 param1 param2 will ouptut : Array ( [0] => test.php5 [1] => -h [2] => -t4 [3] => param1 [4] => param2 ) Array ( [0] => test.php5 [1] => param1 [2] => param2 ) >php shift_test.php5 -h -t 4 param1 param2 will ouptut : Array ( [0] => test.php5 [1] => -h [2] => -t [3] => 4 [4] => param1 [5] => param2 ) Array ( [0] => test.php5 [1] => param1 [2] => param2 )
After getopt() of PHP5.3.0 (on Windows) ignored some parameters if there was a syntactical problem, I decided to code my own generic parameter parser. A call like: php.exe -f test.php -- alfons -a 1 -b2 -c --d 2 --e=3=4 --f "alber t" hans wurst and an in-program call parseParameters(array('f')); would yield in a resulting array: Array ( [0] => alfons [a] => 1 [b2] => 1 [c] => 1 [d] => 2 [e] => 3=4 [f] => 1 [1] => alber t [2] => hans [3] => wurst ) As you can see, values without an identifier are stored with numeric indexes. Existing identifiers without values get "true".
There are 2 simpler (and much faster) methods for getting good getopt() operation without creating your own handler. 1. Use the Console_Getopt PEAR class (should be standard in most PHP installations) which lets you specify both short and long form options as well as whether or not arguments supplied to an option are themselves 'optional'. Very simple to use and requires very little code to operate compaired to writing own handler. 2. If you cannot load external PEAR objects, use your shell's getopt() functions (which in BASHs case work very well) to process options and have your shell script then call your PHP script with a rigid argument structure that is very easy for PHP to digest such as: % myfile.php -a TRUE -b FALSE -c ARGUMENT ... If the initial arguments are invalid you can have the shell script return an error without calling the PHP script. Sounds convoluted but is a very simple solution and in fact PHP's own % pear command uses this method. /usr/bin/pear is a shell script that does some simle checking before calling pearcmd.php and repassing the arguments on to it. The second method is by far the best for portability because it allows a single shell script to check a few things like your PHP version and respond acordingly e.g. does it call your PHP4 or PHP5 compatible script? Also, because getopt() is not available on Windows, The second solution allows you to do Windows specific testing as a BAT file (as oposed to BASH, ZSH or Korn on UNIX).
As already mentioned getopt() will stop parsing options upon the '--'. Sometimes you will have options and arguments but the user may not always provide the explicit -- option. Below is a quick way to collect options and arguments regardless of the -- consistently. #!/usr/bin/php
This is how I handle arguments with getopt: I use switch within a foreach at the beginning of a program.
Here's another way of removing options found by getopt() from the argv[] array. It handles the different kind of parameters without eating chunks that do not belong to an --option. (-nr foo param1 param2 foo)
After you use the getopt function you can use the following script to update the $argv array: Note: I used the array_merge function to reindex the array's keys. Cheers, Koen Bollen
It seems under PHP 5.3.2, getopt() makes a script fail to load if called via HTTP without any conditions. You'll need something like if(isset($_SERVER['argc'])) $args = getopt(); to prevent that.
Beware, this function can be dangerous for options following arguments when, for example, you make use of a --dry-run option, due to this behaviour: "Note: The parsing of options will end at the first non-option found, anything that follows is discarded." My script was doing a live run even though I specified --dry-run as the last part of the command like this `php foo.php arg1 --dry-run`: getopt() did NOT include dry-run in its list of options resulting in my script executing a live run.
when using -f option to indicate script name, php does not allow to use double dash -- to define options after the script name; For example, the following command cannot be execute: php -f myscript.php --config "myconfig.ini"
$opts = getopt('', $params = ['ogrn:','inn:','kpp::','host:','port:','user:','pass:','path:','pattern:']) + ['kpp' => 0,'port' => 21,'path' => '/','pattern' => '.+\.dbf']; array_map(function ($param) use ($opts) { $matches = []; if ((bool)preg_match('/(?[^:\s]+)\b:$/sU', $param, $matches) && (!array_key_exists($matches['param'], $opts) || empty($opts[$matches['param']]))) die(sprintf('1%s not set', $matches['param'])); }, $params);
if you use command like below php [filename] [argument without (-) ] [options] getopt don't return value. you can use this function function getoptions() { global $argv,$argc; $options = array(); for($i = 0;$i 1 && $arg[0] == '-') { if($arg[1] == '-' && $i + 1About getopt(String): Parses the command-line arguments into an associative array, using the function's String parameter to specify arguments and options, thus: * arguments are specified as any letter followed by a colon, e.g. "h:". * arguments are returned as "h" => "value". * options are specified as any letter not followed by a colon, e.g. "r". * options are returned as "r" => (boolean) false. Also note that: 1) Options or arguments not passed in the command-line parameters are not set in the returned associative array. 2) Options or arguments present in the command-line arguments multiple times are returned as an enumerated array within the returned associative array.Your description on getopt is either wrong or the documentation of the function is wrong. -- snippet -- array getopt ( string $options [, array $longopts [, int &$optind ]] ) -- As I read this only the first parameter string $options is required. -- snippet -- longopts An array of options. Each ... optind If the optind parameter is present, ... -- This means that "longopts" is optional, but the third parameter "optind" is required (although the description leaves room for interpretation). This is against the possibilities of PHP because when a parameter is declared optional all following parameters must be declared optional as well. See http://php.net/manual/en/functions.arguments.php and #5. The immutable embedded stub (PHPStorm) [ https://github.com/JetBrains/phpstorm-stubs/blob/master/standard/standard_3.php ] specifies this: -- snippet -- function getopt ($options, array $longopts = null, &$optind) {} -- Which is also wrong, but probably based upon this documentation.
鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com
免责声明:我们致力于保护作者版权,注重分享,当前被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理!邮箱:344225443@qq.com)
图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!
内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)