Php command line console

Php command line console

    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.

Читайте также:  Social network engine php

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:

Читайте также:  Principal components analysis python

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.

Источник

Консольные команды на PHP

У многих, равно как и у меня, периодически возникает потребность в реализации каких-то небольших задач. Например распарсить сайт/API и сохранить данные в xml/json/csv, произвести какие-либо расчеты/пересчеты, перегнать данные из одного формата в другой, собрать статистику и т.д. и т.п. Замечу, что речь о задачах не связанных с текущими проектами.

Собирать тяжелый фреймворк ради удобных фич, лень, а реализовывать в рамках кода текущих проектов как-то не эстетично. Поэтому для экономии своего времени приходится создавать скрипт, копипастить в него куски кода из предыдущих наработок, подключать разнообразные библиотеки и запускать скрипт из консоли. При этом часто требуется некоторая интерактивность работы скрипта: обработка опций/аргументов, а то и диалоговое взаимодействие. Здесь главное чтобы не было настроения, которое хорошо описывается выражением «Аппетит приходит во время еды», тогда вообще не понятно к чему приведет работа над простой задачкой =)

В такие моменты я вспоминал удобную симфоническую консоль, к которой успел привыкнуть работая с проектами на
Symfony 2. Не в обиду другим консолям (zend, yii, django, ror etc), все хороши, просто так сложилось.

Когда в очередной раз потребовалось что-то распарсить, я опять вспомнил про консоль Symfony (Console Component) и тот факт, что это независимый компонент все больше подтолкнул меня к мысли использовать ее возможности.

  • symfony/console — сама консоль
  • symfony/finder — для поиска и подключения к приложению наших комманд
  • suncat/symfony-console-extra — несколько плюшек для того чтобы это все работало
Читайте также:  Php показать код символа

С помощью Сomposer-а создаем новый проект:

$ composer create-project suncat/console-commands ./cmd 

У меня Composer установлен глобально, поэтому он всегда доступен. Если вы им еще не пользуетесь, то для проверки примера его необходимо установить.

После скачивания приложения и всех зависимостей переходим в созданную директорию:

$ cd cmd # для примера, при создании проекта задайте имя директории на свое усмотрение 
app/ console # консоль src/ # автозагрузка psr-0 Command/ # классы ваших команд vendor/ # сторонние библиотеки 

Если видим справочную информацию и список доступных команд значит все ок. Выглядит это так:

Теперь создадим шаблон класса команды, которую мы планируем использовать для реализации задачи:

Please enter the name of the command class: NewsInternetCommand 
Generated new command class to "./cmd/src/Command/NewsInternetCommand.php" 

Собственно все, команда готова, она появилась в списке доступных команд:

Но пока она не делает того что нужно (здесь можно открыть созданный класс в IDE или любимом редакторе и написать код команды).

Так как для нашего примера необходимо получать внешний контент и нам нравится ООП, поставим еще одну библиотеку:

$ composer require kriswallsmith/buzz 0.9 

Buzz — легкий HTTP клиент на PHP5.3. Будем использовать его для выполнения запросов к сервису новостей.

Создадим отдельный класс — YandexRSSNewsParser, который будет предоставлять классу команде подготовленный контент:

// ./src/Parser/YandexRSSNewsParser.php namespace Parser; use Buzz\Client\FileGetContents; use Buzz\Message\Request; use Buzz\Message\Response; use DOMDocument; use DOMXPath; class YandexRSSNewsParser < private $method; private $host; /** * Construct */ public function __construct() < $this->method = 'GET'; $this->host = 'http://news.yandex.ru'; > /** * Get news * * @param $resource * * @return mixed */ public function getNews($resource) < // content $xml = $this->getData($resource); if (false === $xml) < return array(); >$doc = new DOMDocument(); @$doc->loadXML($xml); $xpath = new DOMXpath($doc); // items $items = $xpath->query('.//item'); $news = array(); foreach ($items as $item) < $news[] = array( 'datetime' =>$xpath->evaluate("./pubDate", $item)->item(0)->nodeValue, 'title' => $xpath->evaluate("./title", $item)->item(0)->nodeValue ); > return $news; > /** * Get data * * @return mixed */ protected function getData($resource) < $request = new Request($this->method, $resource, $this->host); $response = new Response(); $client = new FileGetContents(); // processing get data $attempt = 0; do < if ($attempt) < sleep($attempt); >try < $client->send($request, $response); > catch (\Exception $e) < continue; >> while (false === ($response instanceof Response) && ++$attempt < 5); if (false === ($response instanceof Response) || false === $response->isOk()) < return false; >$data = $response->getContent(); return $data; > > 

И отредактируем класс команды, для вывода в консоль заголовков последних новостей, рубрики «Интернет»:

// ./src/Command/NewsInternetCommand.php namespace Command; use Parser\YandexRSSNewsParser; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; /** * NewsInternetCommand */ class NewsInternetCommand extends Command < /** * Configuration of command */ protected function configure() < $this ->setName("news:internet") ->setDescription("Command for parsing internet news") ; > /** * Execute command * * @param \Symfony\Component\Console\Input\InputInterface $input * @param \Symfony\Component\Console\Output\OutputInterface $output */ protected function execute(InputInterface $input, OutputInterface $output) < $parser = new YandexRSSNewsParser(); $output->writeln("Start parsing\n")); // News $news = $parser->getNews('/internet.rss'); foreach ($news as $item) < $output->writeln(sprintf("[%s] %s", $item['datetime'], $item['title'])); > $output->writeln("\nDone!")); > > 

Результат:

Получился очень простой, а за счет symfony/console и composer-а гибкий и удобный инструмент для организации консольных команд на PHP.

Источник

Оцените статью