Принимаем аргументы из командной строки
Вот как обычно бывает: Нам нужно написать малюсенький консольный скрипт бекапа, который, может запускаться из крона, и при этом скрипт должен принимать параметры для соединения с базой данных.
Функции argv и argc#
Самое простейшее что мы начнём писать будет выглядеть примерно так:
// Ожидаем что скрипт будет вызываться с такими параметрами: // php backup.php dbuser dbpassword database host if ($argc != 5) die(PHP_EOL . 'Use: php backup.php dbuser dbpassword database host' . PHP_EOL); > $dbuser = $argv[1]; $dbpassword = $argv[2]; $database = $argv[3]; $host = $argv[4]; $mysql = mysql_connect($host, $dbuser, $dbpassword); mysql_select_db($database, $mysql); // .
Тут мы использовали системную переменную argс для получения количества всех параметров. Запомните, что нулевой параметр (имя скрипта) тут тоже учитывается.
И системную переменную argv с массивом всех параметров.
Для простейшего скрипта этого хватит, но что если мы захотим поддерживать и отдать этот скрипт другим разработчикам?
Скорее всего будет куча ругани в нашу сторону, потому что очень легко можно ошибиться и перепутать местами пароль и базу данных и заметить ошибку будет крайне сложно. Посмотрите:
php backup.php dbuser database dbpassword host
Разбираем параметры с функцией getopt#
Вот тут нам на помощь приходит крайне удобная функция разбора параметров: getopt
Основная мощь getopt в том, что она позволяет нам использовать флаги, обязательные и необязательные параметры в произвольном порядке.
Давайте напишем простой, но очень выразительный пример использования getopt, а потом, посмотрите как люди раньше мучались с регулярками, что бы разобрать командную строку 🙂
// Тут показаны две формы записи аргументов: короткая и полная // При этом, если после параметра стоит два двоеточия, значит параметр необязательный, // а если одно двоеточие - значит обязательный. // все параметры которые не указаны в конфигурации будут проигнорированы $params = array( '' => 'help', 'h::' => 'host::', 'u:' => 'user:', 'p::' => 'password::', 'd:' => 'database:', ); // Default values $host = 'localhost'; $user = 'root'; $password = null; $database = ''; $errors = array(); $options = getopt( implode('', array_keys($params)), $params ); if (isset($options['host']) || isset($options['h'])) $host = isset( $options['host'] ) ? $options['host'] : $options['h']; > if (isset($options['user']) || isset($options['u'])) $port = isset( $options['user'] ) ? $options['user'] : $options['u']; > else $errors[] = 'user required'; > if (isset($options['password']) || isset($options['p'])) $socket = isset( $options['password'] ) ? $options['password'] : $options['p']; > if (isset($options['database']) || isset($options['d'])) $database = isset( $options['database'] ) ? $options['database'] : $options['d']; > else $errors[] = 'database required'; > if ( isset($options['help']) || count($errors) ) $help = " usage: php backup.php [--help] [-h|--host=127.0.0.1] [-u|--user=root] [-p|--password=secret] [-d|--database] Options: --help Show this message -h --host Server hostname (default: localhost) -u --user User -p --password Password (default: no password) -d --database Database Example: php backup.php --user=root --password=secret --database=blog "; if ( $errors ) $help .= 'Errors:' . PHP_EOL . implode("\n", $errors) . PHP_EOL; > die($help); > $mysql = mysql_connect($host, $user, $password); mysql_select_db($database, $mysql); // .
Теперь запустим наш скрипт с параметром –help и порадуемся что хорошо поддерживаемую и понятную программу так легко написать
Если вкратце, то getopt принимает все аргументы из командной строки и складывает валидные параметры в массив $options. А из уже получившегося массива мы можем получить все аргументы и в зависимости от них выдать результат.
Давайте ещё добавим последний штрих, который должен быть во всех наших скриптах:
- Можно убрать расширение php
- В начало каждого скрипта добавим опцию для интерпритатора #!/usr/bin/env php
- Сделаем наши скрипты исполняемыми chmod +x backup.php
После этого можно пользоваться получившимся скриптом как настоящей юникс-программой:
./backup --user=ukko --password=password --database=db1
$argv
Contains an array of all the arguments passed to the script when running from the command line.
Note: The first argument $argv[0] is always the name that was used to run the script.
Note: This variable is not available when register_argc_argv is disabled.
Examples
Example #1 $argv example
When executing the example with: php script.php arg1 arg2 arg3
The above example will output something similar to:
array(4) < [0]=>string(10) "script.php" [1]=> string(4) "arg1" [2]=> string(4) "arg2" [3]=> string(4) "arg3" >
Notes
See Also
User Contributed Notes 6 notes
Please note that, $argv and $argc need to be declared global, while trying to access within a class method.
class A
public static function b ()
var_dump ( $argv );
var_dump (isset( $argv ));
>
>
A :: b ();
?>
will output NULL bool(false) with a notice of «Undefined variable . «
whereas global $argv fixes that.
To use $_GET so you dont need to support both if it could be used from command line and from web browser.
foreach ($argv as $arg) $e=explode(» note» >
You can reinitialize the argument variables for web applications.
So if you created a command line, with some additional tweaks you can make it work on the web.
If you come from a shell scripting background, you might expect to find this topic under the heading «positional parameters».
Sometimes $argv can be null, such as when «register-argc-argv» is set to false. In some cases I’ve found the variable is populated correctly when running «php-cli» instead of just «php» from the command line (or cron).
I discovered that `register_argc_argv` is alway OFF if you use php internal webserver, even if it is set to `On` in the php.ini.
What means there seems to be no way to access argv / argc in php internal commandline server.
Php аргументы в командной строке
- Tell PHP to execute a certain file.
$ php my_script.php $ php -f my_script.php
$ php -r 'print_r(get_defined_constants());'
Note: Read the example carefully: there are no beginning or ending tags! The -r switch simply does not need them, and using them will lead to a parse error.
$ some_application | some_filter | php | sort -u > final_output.txt
As with every shell application, the PHP binary accepts a number of arguments; however, the PHP script can also receive further arguments. The number of arguments that can be passed to your script is not limited by PHP (and although the shell has a limit to the number of characters which can be passed, this is not in general likely to be hit). The arguments passed to the script are available in the global array $argv . The first index (zero) always contains the name of the script as called from the command line. Note that, if the code is executed in-line using the command line switch -r, the value of $argv[0] will be «Standard input code» ; prior to PHP 7.2.0, it was a dash ( «-» ) instead. The same is true if the code is executed via a pipe from STDIN .
A second global variable, $argc , contains the number of elements in the $argv array (not the number of arguments passed to the script).
As long as the arguments to be passed to the script do not start with the — character, there’s nothing special to watch out for. Passing an argument to the script which starts with a — will cause trouble because the PHP interpreter thinks it has to handle it itself, even before executing the script. To prevent this, use the argument list separator — . After this separator has been parsed by PHP, every following argument is passed untouched to the script.
# This will not execute the given code but will show the PHP usage $ php -r 'var_dump($argv);' -h Usage: php [options] [-f] [args. ] [. ] # This will pass the '-h' argument to the script and prevent PHP from showing its usage $ php -r 'var_dump($argv);' -- -h array(2) < [0]=>string(1) "-" [1]=> string(2) "-h" >
However, on Unix systems there’s another way of using PHP for shell scripting: make the first line of the script start with #!/usr/bin/php (or whatever the path to your PHP CLI binary is if different). The rest of the file should contain normal PHP code within the usual PHP starting and end tags. Once the execution attributes of the file are set appropriately (e.g. chmod +x test), the script can be executed like any other shell or perl script:
Example #1 Execute PHP script as shell script
Assuming this file is named test in the current directory, it is now possible to do the following:
$ chmod +x test $ ./test -h -- foo array(4) < [0]=>string(6) "./test" [1]=> string(2) "-h" [2]=> string(2) "--" [3]=> string(3) "foo" >
As can be seen, in this case no special care needs to be taken when passing parameters starting with — .
The PHP executable can be used to run PHP scripts absolutely independent of the web server. On Unix systems, the special #! (or «shebang») first line should be added to PHP scripts so that the system can automatically tell which program should run the script. On Windows platforms, it’s possible to associate php.exe with the double click option of the .php extension, or a batch file can be created to run scripts through PHP. The special shebang first line for Unix does no harm on Windows (as it’s formatted as a PHP comment), so cross platform programs can be written by including it. A simple example of writing a command line PHP program is shown below.
Example #2 Script intended to be run from command line (script.php)
if ( $argc != 2 || in_array ( $argv [ 1 ], array( ‘—help’ , ‘-help’ , ‘-h’ , ‘-?’ ))) ?>
This is a command line PHP script with one option.
can be some word you would like
to print out. With the —help, -help, -h,
or -? options, you can get this help.
The script above includes the Unix shebang first line to indicate that this file should be run by PHP. We are working with a CLI version here, so no HTTP headers will be output.
The program first checks that there is the required one argument (in addition to the script name, which is also counted). If not, or if the argument was —help, -help, -h or -?, the help message is printed out, using $argv[0] to dynamically print the script name as typed on the command line. Otherwise, the argument is echoed out exactly as received.
To run the above script on Unix, it must be made executable, and called simply as script.php echothis or script.php -h. On Windows, a batch file similar to the following can be created for this task:
Example #3 Batch file to run a command line PHP script (script.bat)
@echo OFF "C:\php\php.exe" script.php %*
Assuming the above program is named script.php , and the CLI php.exe is in C:\php\php.exe , this batch file will run it, passing on all appended options: script.bat echothis or script.bat -h.
See also the Readline extension documentation for more functions which can be used to enhance command line applications in PHP.
On Windows, PHP can be configured to run without the need to supply the C:\php\php.exe or the .php extension, as described in Command Line PHP on Microsoft Windows.
Note:
On Windows it is recommended to run PHP under an actual user account. When running under a network service certain operations will fail, because «No mapping between account names and security IDs was done».
User Contributed Notes 7 notes
On Linux, the shebang (#!) line is parsed by the kernel into at most two parts.
For example:
1: #!/usr/bin/php
2: #!/usr/bin/env php
3: #!/usr/bin/php -n
4: #!/usr/bin/php -ddisplay_errors=E_ALL
5: #!/usr/bin/php -n -ddisplay_errors=E_ALL
1. is the standard way to start a script. (compare «#!/bin/bash».)
2. uses «env» to find where PHP is installed: it might be elsewhere in the $PATH, such as /usr/local/bin.
3. if you don’t need to use env, you can pass ONE parameter here. For example, to ignore the system’s PHP.ini, and go with the defaults, use «-n». (See «man php».)
4. or, you can set exactly one configuration variable. I recommend this one, because display_errors actually takes effect if it is set here. Otherwise, the only place you can enable it is system-wide in php.ini. If you try to use ini_set() in your script itself, it’s too late: if your script has a parse error, it will silently die.
5. This will not (as of 2013) work on Linux. It acts as if the whole string, «-n -ddisplay_errors=E_ALL» were a single argument. But in BSD, the shebang line can take more than 2 arguments, and so it may work as intended.
Summary: use (2) for maximum portability, and (4) for maximum debugging.