Перейти к содержимому

Php cli что это

  • автор:

Command Line Interface в PHP

До этого момента мы с Вами знали, что PHP работает на сервере. Клиент обращается к серверу по протоколу HTTP с каким-либо запросом, запрос на сервере обрабатывается и формируется ответ. После этого клиенту снова по протоколу HTTP в ответе отдаётся сформированный ответ. Однако, если взять какой-нибудь более-менее продвинутый сайт, то мы увидим, что есть задачи, которые не решаются стандартным клиент-серверным путем. Например: поздравлять пользователей с днём рождения и дарить им скидку на какой-нибудь продукт. Для того, чтобы это сделать, нам придется обновлять раз в день php-скрипт в браузере, чтобы он выбирал пользователей, у которых сегодня ДР, затем создавал для них скидки, и отправлял им сообщения по почте. Согласитесь, неудобно это делать вручную и в браузере. Для таких случаев в PHP предусмотрен Command Line Interface (CLI) – интерфейс командной строки.

CLI позволяет запускать программы на PHP не через привычную нам клиент-серверную архитектуру, а как простые программы в командной строке. Давайте создадим простейший скрипт, чтобы показать, как это работает. Создаём новую папку bin в корне проекта, а в ней файл – cli.php.

CLI контроллер

Пишем простейший код:

OpenServer cmd

А теперь запускаем консоль из OpenServer:

Переходим в папку с нашим проектом, выполнив:

cd domains\myproject.loc

И пишем следующую команду:

php bin/cli.php

Вывод результата в терминал

В ответ получаем:

Написали простейшее консольное приложение! Уже неплохо. Но что если мы захотим сложить 2 числа, которые нужно передать скрипту? Как Вы понимаете, сделать это с помощью GET- или POST- запросов уже не получится. Так как же быть?

Аргументы консольного приложения

Аргументы консольного приложения

На помощь нам приходят аргументы, которые мы можем передать в скрипт, указав их после имени скрипта в командной строке. Вот так:

А для того, чтобы получить к ним доступ из php-скрипта используется магическая переменная $argv. Она представляет собой массив, в котором нулевой элемент – это путь до скрипта, а все последующие – это его аргументы в консоли.

Вывод аргументов

Давайте теперь запустим наш скрипт с параметрами:

Как видим, наши аргументы попали в этот массив. Давайте напишем простейший скрипт, который будет складывать все переданные ему аргументы.

 echo $sum;

Сумма всех аргументов

Запустим его, и убедимся, что все работает:

И он действительно работает: 3 + 4 + 5 = 12.

Именованные аргументы

А что если мы хотим передавать аргументы с именами? Вроде такого:

И затем в коде получать их в коде по их именам? Для этого нам следует написать простейший парсер, который будет находить вот такие именованные параметры и их значения. Пишем.

 > var_dump($params);

аргументы в массиве

И проверяем его работу:

Отлично, теперь мы можем обращаться к элементам массива params, чтобы выяснить, были ли нам переданы какие-то аргументы или нет.

CLI и ООП

Мы с вами изучили некоторые основы работы с CLI. Давайте теперь перенесем эти знания на объектно-ориентированный подход и научимся работать через интерфейс командной строки с объектами.

Папка для команд

Для этого нам понадобится создать отдельную директорию под «команды». Команды – так мы будем называть наши специальные классы, которые будут выполнять какой-то код через запуск из командной строки. Создаем новую директорию: src/MyProject/Cli.

И теперь создадим наш первый класс, который будет заниматься тем, что считает сумму переданных в него аргументов: -a и -b.

params = $params; $this->checkParams(); > public function execute() < echo $this->getParam('a') + $this->getParam('b'); > private function checkParams() < $this->ensureParamExists('a'); $this->ensureParamExists('b'); > private function getParam(string $paramName) < return $this->params[$paramName] ?? null; > private function ensureParamExists(string $paramName) < if (!isset($this->params[$paramName])) < throw new CliException('Param with name "' . $paramName . '" is not set!'); >> >

В конструкторе класса мы принимаем список параметров, сохраняем их, а затем вызываем метод checkParams(), который проверяет наличие обязательных параметров для этого скрипта. В нём просто поочередно вызывается метод для проверки в массиве нужных ключей. Если их нет – метод кинет исключение. И, наконец, есть метод execute(), который содержит бизнес-логику. В нем используется метод getParam(), который вернет параметр (при его наличии), либо вернет null (при его отсутствии).

И также создаём исключение, специально для ошибок, возникающих при работе с CLI.

Теперь давайте снова вернемся в нашу точку входа для консольных приложений cli.php. Этот файл можно назвать фронт-контроллером для консольных команд, он как index.php в случае с клиент-серверным подходом будет создавать другие объекты и запускать весь процесс.

Дополним этот код так, чтобы он создавал экземпляр нужного класса и передавал ему аргументы.

); // Составляем полное имя класса, добавив нэймспейс $className = '\\MyProject\\Cli\\' . array_shift($argv); if (!class_exists($className)) < throw new \MyProject\Exceptions\CliException('Class "' . $className . '" not found'); >// Подготавливаем список аргументов $params = []; foreach ($argv as $argument) < preg_match('/^-(.+)=(.+)$/', $argument, $matches); if (!empty($matches)) < $paramName = $matches[1]; $paramValue = $matches[2]; $params[$paramName] = $paramValue; >> // Создаём экземпляр класса, передав параметры и вызываем метод execute() $class = new $className($params); $class->execute(); > catch (\MyProject\Exceptions\CliException $e) < echo 'Error: ' . $e->getMessage(); >

Сумматор

Теперь мы можем запустить наш скрипт с помощью вот такой команды:

Если мы захотим создать еще один класс, в котором мы будем вычитать из аргумента a аргумент b, то нам нужно будет продублировать довольно большой объем кода. Но ведь если присмотреться – большую часть кода из класса Summator можно вынести в отдельный класс и использовать его повторно.

Давайте создадим абстрактный класс, который будет заниматься тем, что будет сохранять переданные в него параметры и запускать метод для их проверки.

params = $params; $this->checkParams(); > abstract public function execute(); abstract protected function checkParams(); protected function getParam(string $paramName) < return $this->params[$paramName] ?? null; > protected function ensureParamExists(string $paramName) < if (!isset($this->params[$paramName])) < throw new CliException('Param with name "' . $paramName . '" is not set!'); >> >

Теперь нам в классе Summator достаточно отнаследоваться от этого класса и он значительно упростится:

ensureParamExists('a'); $this->ensureParamExists('b'); > public function execute() < echo $this->getParam('a') + $this->getParam('b'); > >

Результат суммы в терминале

Запустим скрипт снова и убедимся, что все успешно отработало:

Давайте создадим по аналогии скрипт, который будет вычитать из аргумента x аргумент y.

ensureParamExists('x'); $this->ensureParamExists('y'); > public function execute() < echo $this->getParam('x') - $this->getParam('y'); > >

Разница в консоли

Проверим его в деле:

Ошибка об отсутствии обязательного аргумента

А теперь давайте попробуем не указать один из аргументов – получим ошибку.

Вот таким вот нехитрым образом мы с вами научились создавать простейшие программы для запуска в консоли на PHP. А в следующем уроке мы с вами научимся запускать эти команды по расписанию.

Command line php windows: описание и использование

Command line php windows — это инструмент, который позволяет запускать и выполнять PHP-скрипты прямо из командной строки Windows. Это мощный инструмент для разработчиков, которые предпочитают работать с командной строкой вместо графического интерфейса.

Использование Command line php windows позволяет разработчикам управлять и отлаживать свои PHP-скрипты намного эффективнее. Он предоставляет функции, которые не доступны через обычный веб-браузер, такие как доступ к переменным окружения, управление путями поиска и выполнение команд PHP из любой директории.

Для использования Command line php windows вам понадобится установить PHP на ваш компьютер и добавить его в переменную среды PATH. После этого вы сможете запускать PHP-скрипты из командной строки, просто вызывая команду «php». Вы также можете использовать различные флаги и параметры с этой командой, чтобы настроить и управлять выполнением своих скриптов.

Command line php windows является незаменимым инструментом для разработчиков, позволяющим быстро и эффективно выполнять и отлаживать PHP-скрипты. Он дает больше возможностей и контроля, чем использование только графического интерфейса, и позволяет сделать вашу работу с PHP более гибкой и эффективной.

Что такое Command line PHP Windows?

PHP CLI для Windows предоставляет возможность запускать PHP-скрипты, как в интерактивном режиме, так и в автоматическом режиме. Использование командной строки позволяет свободно выполнять PHP-код без необходимости создания отдельных веб-страниц и запросов к серверу.

Command line PHP для Windows предоставляет широкий набор функциональных возможностей, схожих с теми, что доступны в PHP для веб-серверов. Вы можете использовать команды и функции для манипуляции файлами и директориями, работать с базами данных, выполнять управление системными процессами и многие другие операции.

PHP CLI для Windows также предоставляет возможность передачи аргументов командной строки в PHP-скрипт. Вы можете передавать параметры и данные извне, что делает командную строку еще более гибкой и полезной инструментом разработки и автоматизации задач.

Использование Command line PHP для Windows может быть особенно полезным в различных сценариях, таких как автоматизация задач, создание и обновление баз данных, управление серверами, разработка и тестирование скриптов без необходимости запускать веб-сервер и многое другое.

Использование PHP в командной строке

You can easily parse command line arguments into the $_GET variable by using the parse_str() function.

?>

It behaves exactly like you’d expect with cgi-php.

$ php -f somefile.php a=1 b[]=2 b[]=3

This will set $_GET[‘a’] to ‘1’ and $_GET[‘b’] to array(‘2’, ‘3’).

Even better, instead of putting that line in every file, take advantage of PHP’s auto_prepend_file directive. Put that line in its own file and set the auto_prepend_file directive in your cli-specific php.ini like so:

It will be automatically prepended to any PHP file run from the command line.

2 years ago

We can pass many arguments directly into the hashbang line.
As example many ini setting via the -d parameter of php.
—
#!/usr/bin/php -d memory_limit=2048M -d post_max_size=0
phpinfo();
exit;
—
./script | grep memory
memory_limit => 2048M => 2048M
—
But we can also use this behaviour into a second script, so it call the first as an interpreter, via the hashbang:
—
#!./script arg1 arg2 arg3
—
However the parameters are dispatched in a different way into $argv

All the parameters are in $argv[1], $argv[0] is the interpreter script name, and $argv[1] is the caller script name.

To get back the parameters into $argv, we can simply test if $argv[1] contains spaces, and then dispatch again as normal:

#!/usr/bin/php -d memory_limit=2048M -d post_max_size=0
var_dump ( $argv );
if ( strpos ( $argv [ 1 ], ‘ ‘ ) !== false ) $argw = explode ( » » , $argv [ 1 ]);
array_unshift ( $argw , $argv [ 2 ]);
$argv = $argw ;
>
var_dump ( $argv ); ?>
—
array(3) [0]=>
string(8) «./script»
[1]=>
string(15) «arg1 arg2 arg3 »
[2]=>
string(14) «./other_script»
>
array(4) [0]=>
string(8) «./other_script»
[1]=>
string(4) «arg1»
[2]=>
string(4) «arg2»
[3]=>
string(4) «arg3»
>
—
This will maintain the same behaviour in all cases and allow to even double click a script to call both parameters of another script, and even make a full interpreter language layer. The other script doesn’t has to be php. Take care of paths.

5 years ago

Adding a pause() function to PHP waiting for any user input returning it:

function pause () $handle = fopen ( «php://stdin» , «r» );
do < $line = fgets ( $handle ); >while ( $line == » );
fclose ( $handle );
return $line ;
>
?>

18 years ago

When you’re writing one line php scripts remember that ‘php://stdin’ is your friend. Here’s a simple program I use to format PHP code for inclusion on my blog:

UNIX:
cat test.php | php -r «print htmlentities(file_get_contents(‘php://stdin’));»

DOS/Windows:
type test.php | php -r «print htmlentities(file_get_contents(‘php://stdin’));»

8 years ago

Parsing commandline argument GET String without changing the PHP script (linux shell):
URL: index.php?a=1&b=2
Result: output.html

echo «» | php -R ‘include(«index.php»);’ -B ‘parse_str($argv[1], $_GET);’ ‘a=1&b=2’ >output.html

(no need to change php.ini)

You can put this
echo «» | php -R ‘include(«‘$1′»);’ -B ‘parse_str($argv[1], $_GET);’ «$2»
in a bash script «php_get» to use it like this:
php_get index.php ‘a=1&b=2’ >output.html
or directed to text browser.
php_get index.php ‘a=1&b=2’ |w3m -T text/html

16 years ago

Just another variant of previous script that group arguments doesn’t starts with ‘-‘ or ‘—‘

function arguments ( $argv ) <
$_ARG = array();
foreach ( $argv as $arg ) <
if ( ereg ( ‘—([^=]+)=(.*)’ , $arg , $reg )) <
$_ARG [ $reg [ 1 ]] = $reg [ 2 ];
> elseif( ereg ( ‘^-([a-zA-Z0-9])’ , $arg , $reg )) <
$_ARG [ $reg [ 1 ]] = ‘true’ ;
> else <
$_ARG [ ‘input’ ][]= $arg ;
>
>
return $_ARG ;
>

print_r ( arguments ( $argv ));
?>

$ php myscript.php —user=nobody /etc/apache2/*
Array
(
[input] => Array
(
[0] => myscript.php
[1] => /etc/apache2/apache2.conf
[2] => /etc/apache2/conf.d
[3] => /etc/apache2/envvars
[4] => /etc/apache2/httpd.conf
[5] => /etc/apache2/mods-available
[6] => /etc/apache2/mods-enabled
[7] => /etc/apache2/ports.conf
[8] => /etc/apache2/sites-available
[9] => /etc/apache2/sites-enabled
)

20 years ago

I had a problem with the $argv values getting split up when they contained plus (+) signs. Be sure to use the CLI version, not CGI to get around it.

7 years ago

use » instead of ‘ on windows when using the cli version with -r

php -r «echo 1»
— correct

php -r ‘echo 1’
PHP Parse error: syntax error, unexpected »echo’ (T_ENCAPSED_AND_WHITESPACE), expecting end of file in Command line code on line 1

13 years ago

If you want to be interactive with the user and accept user input, all you need to do is read from stdin.

echo «Are you sure you want to do this? Type ‘yes’ to continue: » ;
$handle = fopen ( «php://stdin» , «r» );
$line = fgets ( $handle );
if( trim ( $line ) != ‘yes’ ) echo «ABORTING!\n» ;
exit;
>
echo «\n» ;
echo «Thank you, continuing. \n» ;
?>

4 years ago

When using the -R flag, the name of the variable containing the content of the current line (not including the LF) is $argn.

For example you can do this code:

cat file.txt | php -R ‘echo $argn . «\n»;’

This will just output each line of the input file without doing anything to it.

10 years ago

If you edit a php file in windows, upload and run it on linux with command line method. You may encounter a running problem probably like that:

[root@ItsCloud02 wsdl]# ./lnxcli.php
Extension ‘./lnxcli.php’ not present.

Or you may encounter some other strange problem.
Care the enter key. In windows environment, enter key generate two binary characters ‘0D0A’. But in Linux, enter key generate just only a ‘OA’.
I wish it can help someone if you are using windows to code php and run it as a command line program on linux.

19 years ago

Just a note for people trying to use interactive mode from the commandline.

The purpose of interactive mode is to parse code snippits without actually leaving php, and it works like this:

[root@localhost php-4.3.4]# php -a
Interactive mode enabled

I noticed this somehow got ommited from the docs, hope it helps someone!

12 years ago

Check directly without calling functions:
if ( PHP_SAPI === ‘cli’ )
<
// .
>
?>

You can define a constant to use it elsewhere
define ( ‘ISCLI’ , PHP_SAPI === ‘cli’ );
?>

18 years ago

I needed this, you proly wont tho.
puts the exicution args into $_GET
if ( $argv ) <
foreach ( $argv as $k => $v )
<
if ( $k == 0 ) continue;
$it = explode ( » keyword»>, $argv [ $i ]);
if (isset( $it [ 1 ])) $_GET [ $it [ 0 ]] = $it [ 1 ];
>
>
?>

15 years ago

Parsing command line: optimization is evil!

One thing all contributors on this page forgotten is that you can suround an argv with single or double quotes. So the join coupled together with the preg_match_all will always break that 🙂

Here is a proposal:

#!/usr/bin/php
print_r ( arguments ( $argv ));

function arguments ( $args )
array_shift ( $args );
$endofoptions = false ;

$ret = array
(
‘commands’ => array(),
‘options’ => array(),
‘flags’ => array(),
‘arguments’ => array(),
);

while ( $arg = array_shift ( $args ) )

// if we have reached end of options,
//we cast all remaining argvs as arguments
if ( $endofoptions )
$ret [ ‘arguments’ ][] = $arg ;
continue;
>

// Is it a command? (prefixed with —)
if ( substr ( $arg , 0 , 2 ) === ‘—‘ )

// is it the end of options flag?
if (!isset ( $arg [ 3 ]))
$endofoptions = true ;; // end of options;
continue;
>

$value = «» ;
$com = substr ( $arg , 2 );

// is it the syntax ‘—option=argument’?
if ( strpos ( $com , ‘=’ ))
list( $com , $value ) = split ( » keyword»>, $com , 2 );

// is the option not followed by another option but by arguments
elseif ( strpos ( $args [ 0 ], ‘-‘ ) !== 0 )
while ( strpos ( $args [ 0 ], ‘-‘ ) !== 0 )
$value .= array_shift ( $args ). ‘ ‘ ;
$value = rtrim ( $value , ‘ ‘ );
>

$ret [ ‘options’ ][ $com ] = !empty( $value ) ? $value : true ;
continue;

// Is it a flag or a serial of flags? (prefixed with -)
if ( substr ( $arg , 0 , 1 ) === ‘-‘ )
for ( $i = 1 ; isset( $arg [ $i ]) ; $i ++)
$ret [ ‘flags’ ][] = $arg [ $i ];
continue;
>

// finally, it is not option, nor flag, nor argument
$ret [ ‘commands’ ][] = $arg ;
continue;
>

/* vim: set expandtab tabstop=2 shiftwidth=2: */
?>

13 years ago

Using CLI (on WIN at least), some INI paths are relative to the current working directory. For example, if your error_log = «php_errors.log», then php_errors.log will be created (or appended to if already exists) in whatever directory you happen to be in at the moment if you have write access there. Instead of having random error logs all over the place because of this behavior, you may want to set error_log to a full path, perhaps to the php.exe directory.

16 years ago

In 5.1.2 (and others, I assume), the -f form silently drops the first argument after the script name from $_SERVER[‘argv’]. I’d suggest avoiding it unless you need it for a special case.

18 years ago

One of the things I like about perl and vbscripts, is the fact that I can name a file e.g. ‘test.pl’ and just have to type ‘test, without the .pl extension’ on the windows command line and the command processor knows that it is a perl file and executes it using the perl command interpreter.

I did the same with the file extension .php3 (I will use php3 exclusivelly for command line php scripts, I’m doing this because my text editor VIM 6.3 already has the correct syntax highlighting for .php3 files ).

I modified the PATHEXT environment variable in Windows XP, from the » ‘system’ control panel applet->’Advanced’ tab->’Environment Variables’ button-> ‘System variables’ text area».

Then from control panel «Folder Options» applet-> ‘File Types’ tab, I added a new file extention (php3), using the button ‘New’ and typing php3 in the window that pops up.

Then in the ‘Details for php3 extention’ area I used the ‘Change’ button to look for the Php.exe executable so that the php3 file extentions are associated with the php executable.

You have to modify also the ‘PATH’ environment variable, pointing to the folder where the php executable is installed

Hope this is useful to somebody

21 years ago

To hand over the GET-variables in interactive mode like in HTTP-Mode (e.g. your URI is myprog.html?hugo=bla&bla=hugo), you have to call

php myprog.html ‘&hugo=bla&bla=hugo’

(two & instead of ? and &!)

There just a little difference in the $ARGC, $ARGV values, but I think this is in those cases not relevant.

21 years ago

You can also call the script from the command line after chmod’ing the file (ie: chmod 755 file.php).

On your first line of the file, enter «#!/usr/bin/php» (or to wherever your php executable is located). If you want to suppress the PHP headers, use the line of «#!/usr/bin/php -q» for your path.

16 years ago

Just a variant of previous script to accept arguments with ‘=’ also
function arguments ( $argv ) $_ARG = array();
foreach ( $argv as $arg ) if ( ereg ( ‘—([^=]+)=(.*)’ , $arg , $reg )) $_ARG [ $reg [ 1 ]] = $reg [ 2 ];
> elseif( ereg ( ‘-([a-zA-Z0-9])’ , $arg , $reg )) $_ARG [ $reg [ 1 ]] = ‘true’ ;
>

>
return $_ARG ;
>
?>
$ php myscript.php —user=nobody —password=secret -p —access=»host=127.0.0.1 port=456″
Array
(
[user] => nobody
[password] => secret
[p] => true
[access] => host=127.0.0.1 port=456
)

16 years ago

If your php script doesn’t run with shebang (#!/usr/bin/php),
and it issues the beautifull and informative error message:
«Command not found.» just dos2unix yourscript.php
et voila.

If you still get the «Command not found.»
Just try to run it as ./myscript.php , with the «./»
if it works — it means your current directory is not in the executable search path.

If your php script doesn’t run with shebang (#/usr/bin/php),
and it issues the beautifull and informative message:
«Invalid null command.» it’s probably because the «!» is missing in the the shebang line (like what’s above) or something else in that area.

16 years ago

i use emacs in c-mode for editing. in 4.3, starting a cli script like so:

told emacs to drop into c — mode automatically when i loaded the file for editing . the ‘-q’ flag didn ‘t actually do anything (in the older cgi versions, it suppressed html output when the script was run) but it caused the commented mode line to be ignored by php.

in 5.2, ‘ — q ‘ has apparently been deprecated. replace it with ‘ — ‘ to achieve the 4.3 invocation-with-emacs-mode-line behavior:

don’ t go back to your 4.3 system and replace ‘-q’ with ‘—‘ ; it seems to cause php to hang waiting on STDIN .

20 years ago

Ok, I’ve had a heck of a time with PHP > 4.3.x and whether to use CLI vs CGI. The CGI version of 4.3.2 would return (in browser):
—
No input file specified.
—

And the CLI version would return:
—
500 Internal Server Error
—

It appears that in CGI mode, PHP looks at the environment variable PATH_TRANSLATED to determine the script to execute and ignores command line. That is why in the absensce of this environment variable, you get «No input file specified.» However, in CLI mode the HTTP headers are not printed. I believe this is intended behavior for both situations but creates a problem when you have a CGI wrapper that sends environment variables but passes the actual script name on the command line.

By modifying my CGI wrapper to create this PATH_TRANSLATED environment variable, it solved my problem, and I was able to run the CGI build of 4.3.2

16 years ago

an another «another variant» :

function arguments ( $argv )
$_ARG = array();
foreach ( $argv as $arg )
if ( preg_match ( ‘#^-([a-zA-Z0-9]*)=?(.*)$#’ , $arg , $matches ))
$key = $matches [ 1 ];
switch ( $matches [ 2 ])
case » :
case ‘true’ :
$arg = true ;
break;
case ‘false’ :
$arg = false ;
break;
default:
$arg = $matches [ 2 ];
>
$_ARG [ $key ] = $arg ;
>
else
$_ARG [ ‘input’ ][] = $arg ;
>
>
return $_ARG ;
>
?>

$php myscript.php arg1 -arg2=val2 —arg3=arg3 -arg4 —arg5 -arg6=false

[arg2] => val2
[arg3] => arg3
[arg4] => true
[arg5] => true
[arg5] => false
)

19 years ago

For those of you who want the old CGI behaviour that changes to the actual directory of the script use:
chdir(dirname($_SERVER[‘argv’][0]));

at the beginning of your scripts.

18 years ago

This posting is not a php-only problem, but hopefully will save someone a few hours of headaches. Running on MacOS (although this could happen on any *nix I suppose), I was unable to get the script to execute without specifically envoking php from the command line:

[macg4:valencia/jobs] tim% test.php
./test.php: Command not found.

However, it worked just fine when php was envoked on the command line:

[macg4:valencia/jobs] tim% php test.php
Well, here we are. Now what?

Was file access mode set for executable? Yup.

[macg4:valencia/jobs] tim% ls -l
total 16
-rwxr-xr-x 1 tim staff 242 Feb 24 17:23 test.php

And you did, of course, remember to add the php command as the first line of your script, yeah? Of course.

#!/usr/bin/php

So why dudn’t it work? Well, like I said. on a Mac. but I also occasionally edit the files on my Windows portable (i.e. when I’m travelling and don’t have my trusty Mac available). Using, say, WordPad on Windows. and BBEdit on the Mac.

Aaahhh. in BBEdit check how the file is being saved! Mac? Unix? or Dos? Bingo. It had been saved as Dos format. Change it to Unix:

[macg4:valencia/jobs] tim% ./test.php
Well, here we are. Now what?
[macg4:valencia/jobs] tim%

NB: If you’re editing your php files on multiple platforms (i.e. Windows and Linux), make sure you double check the files are saved in a Unix format. those \r’s and \n’s ‘ll bite cha!

21 years ago

Assuming —prefix=/usr/local/php, it’s better to create a symlink from /usr/bin/php or /usr/local/bin/php to target /usr/local/php/bin/php so that it’s both in your path and automatically correct every time you rebuild. If you forgot to do that copy of the binary after a rebuild, you can do all kinds of wild goose chasing when things break.

20 years ago

In *nix systems, use the WHICH command to show the location of the php binary executable. This is the path to use as the first line in your php shell script file. (#!/path/to/php -q) And execute php from the command line with the -v switch to see what version you are running.

# which php
/usr/local/bin/php
# php -v
PHP 4.3.1 (cli) (built: Mar 27 2003 14:41:51)
Copyright (c) 1997-2002 The PHP Group
Zend Engine v1.3.0, Copyright (c) 1998-2002 Zend Technologies

In the above example, you would use: #!/usr/local/bin/php

Also note that, if you do not have the current/default directory in your PATH (.), you will have to use ./scriptfilename to execute your script file from the command line (or you will receive a «command not found» error). Use the ENV command to show your PATH environment variable value.

17 years ago

Spawning php-win.exe as a child process to handle scripting in Windows applications has a few quirks (all having to do with pipes between Windows apps and console apps).

To do this in C++:

// We will run php.exe as a child process after creating
// two pipes and attaching them to stdin and stdout
// of the child process
// Define sa struct such that child inherits our handles

SECURITY_ATTRIBUTES sa = < sizeof(SECURITY_ATTRIBUTES) >;
sa.bInheritHandle = TRUE;
sa.lpSecurityDescriptor = NULL;

// Create the handles for our two pipes (two handles per pipe, one for each end)
// We will have one pipe for stdin, and one for stdout, each with a READ and WRITE end
HANDLE hStdoutRd, hStdoutWr, hStdinRd, hStdinWr;

// Now we have two pipes, we can create the process
// First, fill out the usage structs
STARTUPINFO si = < sizeof(STARTUPINFO) >;
PROCESS_INFORMATION pi;
si.dwFlags = STARTF_USESTDHANDLES;
si.hStdOutput = hStdoutWr;
si.hStdInput = hStdinRd;

// And finally, create the process
CreateProcess (NULL, «c:\\php\\php-win.exe», NULL, NULL, TRUE, NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi);

// Close the handles we aren’t using
CloseHandle(hStdoutWr);
CloseHandle(hStdinRd);

// Now that we have the process running, we can start pushing PHP at it
WriteFile(hStdinWr, » «, 9, &dwWritten, NULL);

// When we’re done writing to stdin, we close that pipe
CloseHandle(hStdinWr);

// Reading from stdout is only slightly more complicated
int i;

std::string processed(«»);
char buf[128];

// Done reading, so close this handle too
CloseHandle(hStdoutRd);

A full implementation (implemented as a C++ class) is available at http://www.stromcode.com

20 years ago

How to change current directory in PHP script to script’s directory when running it from command line using PHP 4.3.0?
(you’ll probably need to add this to older scripts when running them under PHP 4.3.0 for backwards compatibility)

Here’s what I am using:
chdir(preg_replace(‘/\\/[^\\/]+$/’,»»,$PHP_SELF));

Note: documentation says that «PHP_SELF» is not available in command-line PHP scripts. Though, it IS available. Probably this will be changed in future version, so don’t rely on this line of code.

Use $_SERVER[‘PHP_SELF’] instead of just $PHP_SELF if you have register_globals=Off

18 years ago

dunno if this is on linux the same but on windows evertime
you send somthing to the console screen php is waiting for
the console to return. therefor if you send a lot of small
short amounts of text, the console is starting to be using
more cpu-cycles then php and thus slowing the script.

take a look at this sheme:
cpu-cycle:1 ->php: print(«a»);
cpu-cycle:2 ->cmd: output(«a»);
cpu-cycle:3 ->php: print(«b»);
cpu-cycle:4 ->cmd: output(«b»);
cpu-cycle:5 ->php: print(«c»);
cpu-cycle:6 ->cmd: output(«c»);
cpu-cylce:7 ->php: print(«d»);
cpu-cycle:8 ->cmd: output(«d»);
cpu-cylce:9 ->php: print(«e»);
cpu-cycle:0 ->cmd: output(«e»);

on the screen just appears «abcde». but if you write
your script this way it will be far more faster:
cpu-cycle:1 ->php: ob_start();
cpu-cycle:2 ->php: print(«abc»);
cpu-cycle:3 ->php: print(«de»);
cpu-cycle:4 ->php: $data = ob_get_contents();
cpu-cycle:5 ->php: ob_end_clean();
cpu-cycle:6 ->php: print($data);
cpu-cycle:7 ->cmd: output(«abcde»);

now this is just a small example but if you are writing an
app that is outputting a lot to the console, i.e. a text
based screen with frequent updates, then its much better
to first cach all output, and output is as one big chunk of
text instead of one char a the time.

ouput buffering is ideal for this. in my script i outputted
almost 4000chars of info and just by caching it first, it
speeded up by almost 400% and dropped cpu-usage.

because what is being displayed doesn’t matter, be it 2
chars or 40.0000 chars, just the call to output takes a
great deal of time. remeber that.

maybe someone can test if this is the same on unix-based
systems. it seems that the STDOUT stream just waits for
the console to report ready, before continueing execution.

16 years ago

I was looking for a way to interactively get a single character response from user. Using STDIN with fread, fgets and such will only work after pressing enter. So I came up with this instead:

#!/usr/bin/php -q
function inKey ( $vals ) <
$inKey = «» ;
While(! in_array ( $inKey , $vals )) <
$inKey = trim (` read -s -n1 valu;echo \$valu `);
>
return $inKey ;
>
function echoAT ( $Row , $Col , $prompt = «» ) <
// Display prompt at specific screen coords
echo «\033[» . $Row . «;» . $Col . «H» . $prompt ;
>
// Display prompt at position 10,10
echoAT ( 10 , 10 , «Opt : » );

// Define acceptable responses
$options = array( «1» , «2» , «3» , «4» , «X» );

// Get user response
$key = inKey ( $options );

Php cli что это

Основная цель этого CLI SAPI — разработка консольных приложений на PHP. Имеется довольно много различий между CLI SAPI и другими видами SAPI , которые будут рассмотрены в этой главе. Стоит отметить, что CLI SAPI и CGI — различные SAPI -интерфейсы, хотя в их поведении много общего.

CLI SAPI включается по умолчанию с помощью опции —enable-cli, но может быть выключен опцией —disable-cli при запуске ./configure.

Имя, расположение и существование бинарных модулей CLI / CGI зависит от того, как именно установлен PHP в вашей системе. По умолчанию при выполнении make создаётся как CGI -, так и CLI -модуль, размещённые в директориях sapi/cgi/php-cgi и sapi/cli/php соответственно, внутри директории с исходниками PHP. Следует заметить, что оба файла имеют одинаковое название: php . Что произойдёт при выполнении make install, зависит от того, какие опции вы указали на стадии конфигурирования. Если выбран модуль SAPI во время выполнения, например, apxs, или используется опция опция —disable-cgi, модуль CLI будет скопирован в /bin/php при выполнении make install, в противном случае будет скопирован CGI -модуль. Например, если задана опция —with-apxs, то при выполнении make install CLI -версия будет скопирована в /bin/php . Если вы хотите переопределить установку CGI -модуль, используйте make install-cli после выполнения make install. В качестве альтернативы вы могли бы указать опцию —disable-cgi в строке конфигурации.

Замечание:

Поскольку обе опции, —enable-cli и —enable-cgi, включены по умолчанию, просто наличие —enable-cli в команде конфигурации необязательно означает, что CLI будет скопирован в /bin/php при выполнении make install.

Бинарный файл CLI входит в дистрибутив для Windows в основной папке в качестве файла php.exe . CGI -версия находится в файле php-cgi.exe . Кроме того, в дистрибутив входит файл php-win.exe , если PHP был сконфигурирован с помощью —enable-cli-win32. Он полностью эквивалентен CLI -версии, за исключением того, что абсолютно ничего не выводит, и, таким образом, не предоставляет консоль (окно терминала не появляется на экране).

Замечание: Какой из вариантов SAPI установлен?

Выполните из командной строки php -v для получения информации о том, является ли php CGI или CLI . Также вы можете использовать функцию php_sapi_name() или константу PHP_SAPI .

Замечание:

Соответствующую страницу руководства ( man ) Unix можно просмотреть с помощью команды man php в консоли.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *