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

Начиная с версии 4.3.0, PHP поддерживает новый вид SAPI (интерфейс разработки серверных приложений) под названием CLI, что означает интерфейс командной строки. Как видно из названия, этот вид SAPI предназначен для разработки консольных (или даже десктопных) приложений на PHP. Имеется несколько несущественных различий между CLI SAPI и другими видами SAPI, которые будут рассмотрены в этой главе. Будет полезно заметить, что CLI и CGI - различные SAPI-интерфейсы, хотя в их поведении много общего.

Впервые в качестве эксперимента CLI SAPI был включен в релиз PHP 4.2.0, и при запуске скрипта ./configure необходимо было явно указывать опцию --enable-cli. Начиная с PHP 4.3.0, CLI SAPI не является экспериментальным, и опция сборки --enable-cli присутствует по умолчанию. Вы можете отключить CLI SAPI при помощи опции --disable-cli.

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

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

Дистрибутивы для Windows между версиями PHP 4.2.0 и PHP 4.2.3 включают в себя CLI-модуль как php-cli.exe, расположенный в той же директории, что и CGI-модуль php.exe. Начиная с PHP 4.3.0 дистрибутив для Windows влючает в себя CLI-модуль php.exe, расположенный в отдельной директории cli, полное имя - cli/php.exe. Начиная с PHP 5, CLI-модуль расположен в основной директории и называется php.exe. CGI-модуль также включен в дистрибутив под названием php-cgi.exe.

Начиная с PHP 5, в дистрибутив для Windows входит новый файл php-win.exe. Он полностью эквивалентен CLI, за исключением того, что php-win абсолютно ничего не выводит, что приводит к отстутствию консоли (окно DOS не появляется на экране). Это поведение похоже на php-gtk. При сборке из исходных кодов вам необходимо указать опцию --enable-cli-win32.

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

Замечание: Соответствующая страница руководства Unix была добавлена в PHP 4.3.2. Вы можете увидеть ее, выполнив в консоли man php.

Основные отличия CLI SAPI от остальных реализаций SAPI:

  • В отличие от CGI SAPI заголовки не пишутся в поток вывода.

    Несмотря на то, что в CGI SAPI есть способ подавить HTTP-заголовки, в CLI SAPI нет возможности их включить.

    CLI по умолчанию запускается в режиме с подавлением сообщений, тем не менее, ключи -q и --no-header сохранены для обратной совместимости, что позволяет использовать написанные ранее CGI-скрипты.

    Текущая директория не изменяется на рабочую директорию скрипта. (Ключи -C и --no-chdir сохранены для обратной совместимости)

    Сообщения об ошибках выдаются в текстовом режиме (без HTML-форматирования).

  • Некоторые настройки php.ini переопределены в CLI SAPI, поскольку они не имеют особого смысла при работе в командной строке:

    Таблица 43-1. Переопределяемые директивы php.ini

    ДирективаЗначение по умолчанию в CLI SAPIКомментарий
    html_errorsFALSE Бывает достаточно сложно прочитать в консоли сообщение об ошибке, когда оно наполнено бессмысленными HTML-тегами, поэтому значение по умолчанию данной опции всегда FALSE.
    implicit_flushTRUE Желательно, чтобы любой вывод print(), echo(), а также аналогичных функций немедлено отправлялся в стандартный поток вывода, а не попадал в буфер. Хотя вы все еще можете использовать буферизацию вывода, если хотите задержать вывод или манипулировать им.
    max_execution_time0 (без ограничений) Из-за неограниченных возможностей использования PHP в командной строке максимальное время выполнения скрипта не ограничено. В то время, как приложения, написанные для веб, выполняются достаточно быстро, консольные приложения могут выполняться в течении длительного времени.
    register_argc_argvTRUE

    Благодаря значению TRUE в CLI SAPI вам всегда доступны переменные argc (количество аргументов при запуске приложения) и argv (массив текущих аргументов).

    Начиная с PHP 4.3.0, при использовании CLI SAPI переменные $argc и and $argv зарегистрированы и заполнены соответствующими значениями. В более ранних версиях создание этих переменных, так же, как и для CGI или модуля веб-сервера, требует значение on директивы register_globals. Независимо от версии PHP или статуса опции register_global они всегда доступны как элементы массива $_SERVER или $HTTP_SERVER_VARS. Например: $_SERVER['argv']

    Замечание: Эти директивы не могут быть инициализированы другими значениями из конфигурационного файла php.ini или любого другого (в случае, если он указан). Это является ограничением, поскольку указанные выше значения по умолчанию применяются после обработки конфигурационных файлов. Тем не менее, эти значения могут быть изменены во время работы скрипта (хотя это не имеет особого смысла для указанных директив, например, для register_argc_argv).

  • Облегчена работа с консолью, благодаря следующим определенным константам:

    Таблица 43-2. Специфические CLI-константы

    КонстантаОписание
    STDIN Уже открытый поток stdin. Константа хранит результат
    <?php

    $stdin
    = fopen('php://stdin', 'r');

    ?>
    Если вам необходимо прочитать строку из потока stdin, вы можете сделать это следующим образом:
    <?php
      $line
    = trim(fgets(STDIN)); // читаем строку из STDIN
     
    fscanf(STDIN, "%d\n", $number); // читаем число из STDIN
     
    ?>
    STDOUT Уже открытый поток stdout. Константа хранит результат
    <?php

    $stdout
    = fopen('php://stdout', 'w');

    ?>
    STDERR Уже открытый поток stderr. Константа хранит результат
    <?php

    $stderr
    = fopen('php://stderr', 'w');

    ?>

    Имея все это, вы не должны самостоятельно открывать, например, поток для stderr, а просто используйте константу вместо дескриптора потока:
    php -r 'fwrite(STDERR, "stderr\n");'
    Также вам не надо закрывать эти потоки, PHP автоматически закрывает их после завершения скрипта.

  • CLI SAPI не изменяет текущую директорию на директорию исполняемого скрипта!

    Пример, демонстрирующий отличие CGI SAPI:
    <?php
    // Простейший тестовый скрипт под названием test.php
    echo getcwd(), "\n";
    ?>

    В случае, если используется CGI версия, результат работы будет следующим:
    $ pwd
    /tmp
    
    $ php -q another_directory/test.php
    /tmp/another_directory
    Это наглядно демонстрирует тот факт, что PHP изменяет текущую директорию на директорию исполняемого скрипта.

    Использование CLI SAPI дает другой результат:
    $ pwd
    /tmp
    
    $ php -f another_directory/test.php
    /tmp
    Это позволяет писать более гибкие консольные скрипты на PHP.

    Замечание: CGI SAPI позволяет получить аналогичное CLI SAPI поведение в случае использования ключа -C при запуске из командной строки.

Список опций, доступный при запуске PHP из командной строки, может быть получен в любой момент путем запуска PHP с ключом -h:
Usage: php [options] [-f] <file> [args...]
       php [options] -r <code> [args...]
       php [options] [-- args...]
  -s               Отображает исходный код с цветной подсветкой
  -w               Отображает исходный текст без комментариев и пробелов
  -f <file>        Исполняет <file>
  -v               Выводит информацию о версии PHP
  -c <path>|<file> Ищет файл php.ini в указанной директории
  -a               Интерактивный запуск
  -d foo[=bar]     Установить конфигурационную опцию foo значением 'bar'
  -e               Генерация дополнительной информации для отладчика и профайлера
  -z <file>        Загрузить Zend-расширение <file>.
  -l               Проверить синтаксис
  -m               Показать подключенные модули
  -i               Выводит информацию о PHP
  -r <code>        Запустить PHP-код без использования <?..?>
  -h               Текущая справка

  args...          Аргументы, передаваемые скрипту. Используйте -- args в случае, если 
                   первый аргумент начинается с '-' или сам скрипт читается из потока STDIN.

CLI SAPI имеет три различных способа получения PHP-кода, который необходимо выполнить:

  1. Указать PHP на исполнение конкретного файла.

    php my_script.php
    
    php -f my_script.php
    Оба способа (с или без использования ключа -f) исполняют указанный файл my_script.php. Вы можете выбрать любой файл - ваши PHP-скрипты не обязаны заканчиваться на .php, а могут иметь любое имя и расширение.

  2. Указать PHP-код для выполнения непосредственно в командной строке.

    php -r 'print_r(get_defined_constants());'
    Особого внимания требует подстановка переменных окружения и использование кавычек.

    Замечание: Посмотрите внимательно на пример: в нем нет начальных и конечных тегов! При использовании ключа -r они не нужны. Использование их в данном примере приведет к синтаксической ошибке.

  3. Предоставить PHP-код для выполнения посредством стандартного потока stdin.

    Это позволяет динамически создавать PHP-код и переадресовывать его исполняемому модулю, как показано в следующем (вымышленном) примере:
    $ some_application | some_filter | php | sort -u >final_output.txt

Вы не можете комбинировать эти три способа выполнения кода.

Как и в любом консольном приложении, не только PHP, но и сам скрипт может принимать аргументы командной строки. Количество передаваемых аргументов в PHP не ограничено (хотя консоль имеет некоторое ограничение на количество передаваемых символов, но на практике вы не должны с этим столкнуться). Все аргументы, переданные вашему скрипту, доступны в виде глобального массива $argv. Нулевой элемент содержит имя скрипта (которое является символом - в случае, если PHP-код читается из потока stdin или указан в командной строке при помощи ключа -r). Вторая определяемая глобальная переменная $argc содержит количество элементов массива $argvне количество аргументов, передаваемых при запуске).

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

# Приведенный пример не выполнит указанный код, а выдаст справку об использовании PHP
$ php -r 'var_dump($argv);' -h
Usage: php [options] [-f] <file> [args...]
[...]

# Аргумент '-h' будет передан скрипту, справка напечатана не будет
$ php -r 'var_dump($argv);' -- -h
array(2) {
  [0]=>
  string(1) "-"
  [1]=>
  string(2) "-h"
}

Однако, существует еще один способ использования PHP для написания консольных скриптов. Вы можете написать скрипт, первая строка которого начинается с #!/usr/bin/php. Следующие строки содержат обыкновенный PHP-код, обрамленный открывающими и завершающими PHP-тегами. Также необходимо установить права на выполнение (как правило, это chmod +x test), чтобы ваш скрипт мог запускаться, как обыкновенный консольный (или perl) скрипт:
#!/usr/bin/php
<?php
var_dump
($argv);
?>
Предположив, что наш скрипт называется test и расположен в текущей директории, мы можем выполнить следующее:
$ chmod +x test
$ ./test -h -- foo
array(4) {
  [0]=>
  string(6) "./test"
  [1]=>
  string(2) "-h"
  [2]=>
  string(2) "--"
  [3]=>
  string(3) "foo"
}
Как видно из примера, при передаче параметров командной строки, начинающихся с символа -, никаких особых действий предпринимать не надо.

Полные названия опций доступны, начиная с PHP 4.3.3.

Таблица 43-3. Опции, доступные из командной строки

ОпцияПолное названиеОписание
-s--syntax-highlight

Отображает исходный код с цветной подсветкой

Эта опция использует внутренний механизм разбора файла, генерирует подсвеченную HTML-версию и записывает ее в стандартный вывод. Следует заметить, что генерируется только блок <code> [...] </code> с HTML-тегами, без HTML-заголовков.

Замечание: Эта опция не совместима с опцией -r.

-s--syntax-highlighting

Алиас для --syntax-highlight.

-w--strip

Отображает исходный текст без комментариев и пробельных символов.

Замечание: Эта опция не совместима с опцией -r.

-f--file

Исполняет указанный файл. Опция -f является не обязательной и может отсутствовать. Достаточно просто указать имя файла.

-v--version

Выводит информацию о версии PHP, PHP SAPI и Zend, например:
$ php -v
PHP 4.3.0 (cli), Copyright (c) 1997-2002 The PHP Group
Zend Engine v1.3.0, Copyright (c) 1998-2002 Zend Technologies

-c--php-ini

При помощи этой опции можно указать специфическую директорию для конфигурационного файла php.ini либо непосредственно указать на сам INI-файл (название которого может отличаться от стандартного php.ini), например:
$ php -c /custom/directory/ my_script.php

$ php -c /custom/directory/custom-file.ini my_script.php
В случае, если вы не используете данную опцию, конфигурационный файл будет взят из директории по умолчанию.

-n--no-php-ini

Указывает на необходимость игнорировать конфигурационный файл php.ini, доступен, начиная с PHP 4.3.0.

-d--define

Эта опция позволяет устанавливать специальное значение для каждой из конфигурационных переменных, доступных в php.ini. Синтаксис выглядит следующим образом:
-d configuration_directive[=value]

Примеры (переводы строк использованы, чтобы сделать текст более читаемым):
# Если опущено значение, то соответствующей опции будет присвоено значение "1"
$ php -d max_execution_time
        -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(1) "1"

# Указание пустого значения инициализирует соответствующую  опцию значением ""
php -d max_execution_time=
        -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(0) ""

# Конфигурационная переменная будет установлена любым значением, 
# указанным после символа '='

$  php -d max_execution_time=20
        -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(2) "20"
$  php
        -d max_execution_time=doesntmakesense
        -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(15) "doesntmakesense"

-a--interactive

Запускает PHP в интерактивном режиме.

-e--profile-info

Генерирует дополнительную информацию для отладчика и профайлера.

-z--zend-extension

Подгружает дополнительный модуль Zend. В случае, если указано только имя файла, PHP ищет модуль в текущем пути к библиотекам по умолчанию (в Linux-системах он обычно указан в /etc/ld.so.conf). В случае, если указано имя файла и полный путь к нему, поиск в системных библиотеках не производится. Указание относительного пути к модулю приведет к поиску файла по указанному пути относительно текущей директории.

-l--syntax-check

Эта опция предоставляет удобный способ для проверки заданного PHP-кода на наличие синтаксических ошибок. В случае успешной проверки будет напечатана следующая фраза: "No syntax errors detected in <filename>",- и код возврата будет равен 0. А в случае неудачи - текст "Errors parsing <filename>" вместе с внутренними сообщениями разборщика и код возврата 255.

Проверка исходного кода при помощи данной опции не находит фатальных ошибок (например, таких как вызов неопределенных функций). Используйте опцию -f, если вы хотите проверить код на наличие фатальных ошибок.

Замечание: Эта опция не совместима с опцией -r.

-m--modules

При использовании этой опции PHP напечатает список встроенных (а также подгруженных) модулей Zend и PHP.
$ php -m
[PHP Modules]
xml
tokenizer
standard
session
posix
pcre
overload
mysql
mbstring
ctype

[Zend Modules]

-i--info Использование этой опции приводит к вызову функции phpinfo() и и выводу результирующей информации. В случае, если PHP работает некорректно, будет весьма логично выполнить php -i и посмотреть, выводятся ли сообщения об ошибке до информационных таблиц или даже вместо них. Учтите, что в случае использования CGI-модуля весь вывод будет в формате HTML и, как следствие, может выглядеть нечитабельно.
-r--run

Эта опция позволяет выполнять PHP-код, указанный непосредственно в командной строке. Открывающие и завершающие PHP-теги (<?php и ?>) не нужны и, более того, приводят к синтаксической ошибке.

Замечание: При использовании этого ключа следует быть очень осторожным и избегать недоразумений, связанных с автоматической подстановкой переменных окружения.

Вот пример, приводящий к синтаксической ошибке:
$ php -r "$foo = get_defined_constants();"
Command line code(1) : Parse error - parse error, unexpected '='
Проблема заключается в том, что sh/bash выполняет автоматическую подстановку переменных в случае, если используются двойные кавычки ("). Поскольку переменная $foo вряд ли определена, она заменяется пустой строкой, так что передаваемый PHP-код для выполнения выглядит следующим образом:
$ php -r " = get_defined_constants();"
Правильным решением в данном случае будет использование одиночных кавычек ', поскольку автоматическая подстановка переменных, заключенных в одиночные кавычки, в sh/bash не происходит.
$ php -r '$foo = get_defined_constants(); var_dump($foo);'
array(370) {
  ["E_ERROR"]=>
  int(1)
  ["E_WARNING"]=>
  int(2)
  ["E_PARSE"]=>
  int(4)
  ["E_NOTICE"]=>
  int(8)
  ["E_CORE_ERROR"]=>
  [...]
Если вы используете оболочку, отличную от sh/bash, у вас могут возникнуть другие вопросы. В таком случае создайте рапорт о возникшей проблеме на сайте http://bugs.php.net/ или напишите письмо по адресу phpdoc@lists.php.net. Вы вполне можете столкнуться с проблемами при попытке получить доступ к переменным оболочки или при работе с экранирующими обратными слешами. Мы вас предупредили.

Замечание: Ключ -r доступен в CLI SAPI и не доступен в CGI SAPI.

-h--help При помощи этой опции вы можете получить информацию о действующем списке опций командной строки и их краткое описание.
-?--usage Алиас для --help.

Исполняемый PHP-файл может использоваться для запуска PHP-скриптов независимо от веб-сервера. В случае, если вы работаете в Unix-подобной системе, вам необходимо добавить ко всем скриптам специальную первую строку и сделать их исполняемыми, чтобы указать, какая из программ должна обрабатывать эти скрипты. На Windows-платформах вы можете назначить обработчик php.exe для файлов с расширениями .php либо создать пакетный (.bat) файл для запуска скриптов посредством PHP. Строка, добавляемая вначале скрипта для Unix-систем, не влияет на их работу в ОС Windows, таким образом вы можете создавать кроссплатформенные скрипты. Ниже приведен простой пример скрипта, выполняемого из командной строки:

Пример 43-1. Скрипт, предназначенный для запуска из командной строки (script.php)

#!/usr/bin/php
<?php

if ($argc != 2 || in_array($argv[1], array('--help', '-help', '-h', '-?'))) {
?>

Это консольный PHP-скрипт, принимающий один аргумент.

  Использование:
  <?php echo $argv[0]; ?> <option>

  <option> Любое слово, которое вы хотели бы
  напечатать. Опции  --help, -help, -h,
  или -? покажут текущую справочную информацию.

<?php
} else {
   echo
$argv[1];
}
?>

В приведенном примере мы используем специальную первую строку для указания на то, что этот скрипт необходимо запускать при помощи PHP. Поскольку мы работаем с CLI-версией, то HTTP-заголовки выводиться не будут. При написании консольных приложений на PHP вам доступны две переменные: $argc и $argv. Первая - количество переданных аргументов плюс один (имя выполняемого скрипта). Вторая - массив переданных аргументов, начиная с имени скрипта с нулевым индексом ($argv[0]).

Также в приведенном примере мы проверяем количество переданных аргументов. В случае, если их более или менее одного, а также в случае, если переданный аргумент был --help, -help, -h или -?, мы выводим справочное сообщение, подставляя имя выполняемого скрипта динамически. В обратном случае мы просто печатаем полученный аргумент.

Если вы хотите выполнить приведенный пример в Unix-системе, вам необходимо сделать его исполняемым и просто выполнить из консоли script.php echothis или script.php -h. В Windows-системе вы можете создать для этого пакетный файл:

Пример 43-2. Пакетный файл для запуска PHP-скрипта из командной строки (script.bat)

@c:\php\cli\php.exe script.php %1 %2 %3 %4

Предполагая, что скрипт называется script.php и полный путь к CLI php.exe совпадает с c:\php\cli\php.exe, приведенный пакетный файл запустит скрипт с переданными вами параметрами: script.bat echothis либо script.bat -h.

Вы также можете ознакомится с расширением Readline, которое может быть использовано для усовершенствования консольного PHP-скрипта.



Использование PHP в командной строке
stromdotcom at hotmail dot com
21-Feb-2006 10:27
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 create the pipes, and make them inheritable
CreatePipe (&hStdoutRd, &hStdoutWr, &sa, 0))
SetHandleInformation(hStdoutRd, HANDLE_FLAG_INHERIT, 0);
CreatePipe (&hStdinRd, &hStdinWr, &sa, 0)
SetHandleInformation(hStdinWr, HANDLE_FLAG_INHERIT, 0);

// 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, "<?php echo 'test'; ?>", 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];

while ( (ReadFile(hStdoutRd, buf, 128, &dwRead, NULL) && (dwRead != 0)) ) {
   for (i = 0; i < dwRead; i++)
       processed += buf[i];
}   

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

A full implementation (implemented as a C++ class) is available at http://www.stromcode.com
drewish at katherinehouse dot com
25-Sep-2005 12:08
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'));"
OverFlow636 at gmail dot com
19-Sep-2005 12:27
I needed this, you proly wont tho.
puts the exicution args into $_GET
<?php
if ($argv)
   for (
$i=1;$i<count($argv);$i++)
   {
      
$it = split("=",$argv[$i]);
      
$_GET[$it[0]] = $it[1];
   }
?>
php at schabdach dot de
16-Sep-2005 09:06
To pass more than 9 arguments to your php-script on Windows, you can use the 'shift'-command in a batch file. After using 'shift', %1 becomes %0, %2 becomes %1 and so on - so you can fetch argument 10 etc.

Here's an example - hopefully ready-to-use - batch file:

foo.bat:
---------
@echo off

:init_arg
set args=

:get_arg
shift
if "%0"=="" goto :finish_arg
set args=%args% %0
goto :get_arg
:finish_arg

set php=C:\path\to\php.exe
set ini=C:\path\to\php.ini
%php% -c %ini% foo.php %args%
---------

Usage on commandline:
foo -1 -2 -3 -4 -5 -6 -7 -8 -9 -foo -bar

A print_r($argv) will give you all of the passed arguments.
Lasse Johansson
18-Aug-2005 01:53
Hi, parsing the commandline (argv) can be very simple in PHP.
If you use keyword parms like:

script.php parm1=value parm3=value

All you have to do in script.php is:

for ($i=1; $i < $argc; $i++) {parse_str($argv[$i]);}
$startup=compact('parm1', 'parm2', 'parm3');
docey
14-Jul-2005 05:44
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.
wallacebw
24-Jun-2005 08:07
For windows clearing the screen using "system('cls');" does not work (at least for me)...

Although this is not pretty it works... Simply send 24 newlines after the output (for one line of output, 23 for two, etc

Here is a sample function and usage:

   function CLS($lines){  // $lines = number of lines of output to keep
       for($i=24;$i>=$lines;$i--) @$return.="\n";
       return $return;
   }
 
   fwrite(STDOUT,"Still Processing: Total Time ".$i." Minutes so far..." . CLS(1));

Hope This Helps,
Wallacebw
linus at flowingcreativity dot net
30-May-2005 07:32
If you are using Windows XP (I think this works on 2000, too) and you want to be able to right-click a .php file and run it from the command line, follow these steps:

1. Run regedit.exe and *back up the registry.*
2. Open HKEY_CLASSES_ROOT and find the ".php" key.

IF IT EXISTS:
------------------
3. Look at the "(Default)" value inside it and find the key in HKEY_CLASSES_ROOT with that name.
4. Open the "shell" key inside that key. Skip to 8.

IF IT DOESN'T:
------------------
5. Add a ".php" key and set the "(Default)" value inside it to something like "phpscriptfile".
6. Create another key in HKEY_CLASSES_ROOT called "phpscriptfile" or whatever you chose.
7. Create a key inside that one called "shell".

8. Create a key inside that one called "run".
9. Set the "(Default)" value inside "run" to whatever you want the menu option to be (e.g. "Run").
10. Create a key inside "run" called "command".
11. Set the "(Default)" value inside "command" to:

cmd.exe /k C:\php\php.exe "%1"

Make sure the path to PHP is appropriate for your installation. Why not just run it with php.exe directly? Because you (presumably) want the console window to remain open after the script ends.

You don't need to set up a webserver for this to work. I downloaded PHP just so I could run scripts on my computer. Hope this is useful!
roberto dot dimas at gmail dot com
26-May-2005 01:52
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
diego dot rodrigues at poli dot usp dot br
02-May-2005 08:29
#!/usr/bin/php -q
<?
/**********************************************
* Simple argv[] parser for CLI scripts
* Diego Mendes Rodrigues - So Paulo - Brazil
* diego.m.rodrigues [at] gmail [dot] com
* May/2005
**********************************************/

class arg_parser {
   var
$argc;
   var
$argv;
   var
$parsed;
   var
$force_this;

   function
arg_parser($force_this="") {
       global
$argc, $argv;
      
$this->argc = $argc;
      
$this->argv = $argv;
      
$this->parsed = array();
      
      
array_push($this->parsed,
                           array(
$this->argv[0]) );

       if ( !empty(
$force_this) )
           if (
is_array($force_this) )
              
$this->force_this = $force_this;

      
//Sending parameters to $parsed
      
if ( $this->argc > 1 ) {
           for(
$i=1 ; $i< $this->argc ; $i++) {
              
//We only have passed -xxxx
              
if ( substr($this->argv[$i],0,1) == "-" ) {
                  
//Se temos -xxxx xxxx
                  
if ( $this->argc > ($i+1) ) {
                       if (
substr($this->argv[$i+1],0,1) != "-" ) {
                          
array_push($this->parsed,
                               array(
$this->argv[$i],
                                  
$this->argv[$i+1]) );
                          
$i++;
                           continue;
                       }
                   }
               }
              
//We have passed -xxxxx1 xxxxx2
              
array_push($this->parsed,
                                                 array(
$this->argv[$i]) );
           }
       }

              
//Testing if all necessary parameters have been passed
              
$this->force();
   }

  
//Testing if one parameter have benn passed
  
function passed($argumento) {
       for(
$i=0 ; $i< $this->argc ; $i++)
           if (
$this->parsed[$i][0] == $argumento )
               return
$i;
       return
0;
   }

  
//Testing if you have passed a estra argument, -xxxx1 xxxxx2
  
function full_passed($argumento) {
      
$findArg = $this->passed($argumento);
       if (
$findArg )
           if (
count($this->parsed[$findArg] ) > 1 )
               return
$findArg;
       return
0;
   }

      
//Returns  xxxxx2 at a " -xxxx1 xxxxx2" call
  
function get_full_passed($argumento) {
              
$findArg = $this->full_passed($argumento);

               if (
$findArg )
                   return
$this->parsed[$findArg][1];

               return;
       }
  
  
//Necessary parameters to script
  
function force() {
       if (
is_array( $this->force_this ) ) {
           for(
$i=0 ; $i< count($this->force_this) ; $i++) {
               if (
$this->force_this[$i][1] == "SIMPLE"
                    
&& !$this->passed($this->force_this[$i][0])
               )
                   die(
"\n\nMissing " . $this->force_this[$i][0] . "\n\n");

                               if (
$this->force_this[$i][1] == "FULL"
                                    
&& !$this->full_passed($this->force_this[$i][0])
               )
                                       die(
"\n\nMissing " . $this->force_this[$i][0] ." <arg>\n\n");
           }
       }
   }
}

//Example
$forcar = array(
       array(
"-name", "FULL"),
       array(
"-email","SIMPLE") );

$parser = new arg_parser($forcar);

if (
$parser->passed("-show") )
   echo
"\nGoing...:";

echo
"\nName: " . $parser->get_full_passed("-name");

if (
$parser->full_passed("-email") ) 
   echo
"\nEmail: " . $parser->get_full_passed("-email");
else
       echo
"\nEmail: default";

if (
$parser->full_passed("-copy") )
       echo
"\nCopy To: " . $parser->get_full_passed("-copy");

echo
"\n\n";
?>

TESTING
=====
[diego@Homer diego]$ ./en_arg_parser.php -name -email cool -copy Ana

Missing -name <arg>

[diego@Homer diego]$ ./en_arg_parser.php -name diego -email cool -copy Ana

Name: diego
Email: cool
Copy To: Ana

[diego@Homer diego]$ ./en_arg_parser.php -name diego -email  -copy Ana

Name: diego
Email: default
Copy To: Ana

[diego@Homer diego]$ ./en_arg_parser.php -name diego -email

Name: diego
Email: default

[diego@Homer diego]$
rh@hdesigndotdemondotcodotuk
25-Apr-2005 01:28
In a bid to save time out of lives when calling up php from the Command Line on Mac OS X.

I just wasted hours on this. Having written a routine which used the MCRYPT library, and tested it via a browser, I then set up a crontab to run the script from the command line every hour (to do automated backups from mysql using mysqldump, encrypt them using mcrypt, then email them and ftp them off to remote locations).

Everything worked fine from the browser, but failed every time from the cron task with "Call to undefined function: mcrypt [whatever]".

Only after much searching do I realise that the CGI and CLI versions are differently compiled, and have different modules attached (I'm using the entropy.ch install for Mac OS-X, php v4.3.2 and mysql v4.0.18).

I still can not find a way to resolve the problem, so I have decided instead to remove the script from the SSL side of the server, and run it using a crontab with CURL to localhost or 127.0.0.1 in order that it will run through Apache's php module.

Just thought this might help some other people tearing their hair out. If anyone knows a quick fix to add the mcrypt module onto the CLI php without any tricky re-installing, it'd be really helpful.

Meantime the workaround does the job, not as neatly though.
merrittd at dhcmc dot com
28-Mar-2005 01:23
Example 43-2 shows how to create a DOS batch file to run a PHP script form the command line using:

@c:\php\cli\php.exe script.php %1 %2 %3 %4

Here is an updated version of the DOS batch file:

@c:\php\cli\php.exe %~n0.php %*

This will run a PHP file (i.e. script.php) with the same base file name (i.e. script) as the DOS batch file (i.e. script.bat) and pass all parameters (not just the first four as in example 43-2) from the DOS batch file to the PHP file. 

This way all you have to do is copy/rename the DOS batch file to match the name of your PHP script file without ever having to actually modify the contents of the DOS batch file to match the file name of the PHP script.
13-Mar-2005 01:52
Here is very simple, but usefull Command Line handler class. it may be usefull for your apps.

http://www.pure-php.de/node/16
<?
require_once("CliHandler.class.php");

class
AnyClass{
   public function
start(){
       return
"started";
   }
   public function
stop(){
       return
"stoppded";
   }
}
$cli = new CliHandler(new AnyClass());
$cli->run();
?>

CliHandler accepts any class als argument.
Try this.

/usr/local/php/PHP5 CliHandler.class.php
output: Try these command:
start
stop
enter "start"
output: started
bertrand at toggg dot com
07-Mar-2005 08:40
If you want to pass directly PHP code to the interpreter and you don't have only CGI, not the CLI SAPI so you miss the -r option.
If you're lucky enough to be on a nix like system, then tou can still use the pipe solution as the 3. way to command CLI SAPI described above, using a pipe ('|').

Then works for CGI SAPI:

$ echo '<?php echo "coucou\n"; phpinfo(); /* or any code */ ?>' | php

NOTE: unlike commands passed to the -r option, here you NEED the PHP tags.
jeromenelson at gmail dot com
07-Mar-2005 01:21
This is the most simple way to get the named parameter.  Write the script test.php as ...

<?
  
echo "Yo! my name is ".$_REQUEST["name"]."\n";
?>

and run this program as follows

# php -f test.php name=Jerry
Yo! my name is Jerry

I am using PHP 4.3.3 (CGI) in Fedora Core 1 and It is working perfectly

God Bless You!
obfuscated at emailaddress dot com
25-Feb-2005 08:15
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
<?php print "Well, here we are...  Now what?\n"; ?>

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!
db at digitalmediacreation dot ch
22-Feb-2005 11:49
A very important point missing here (I lost hours on it and hope to avoid this to you) :

* When using PHP as CGI
* When you just become crazy because of "No input file specified" appearing on the web page, while it never appears directly in the shell

Then I have a solution for you :

1. Create a script for example called cgiwrapper.cgi
2. Put inside :
 #!/bin/sh -
 export SCRIPT_FILENAME=/var/www/realpage.php
 /usr/bin/php -f $SCRIPT_FILENAME
3. Name your page realpage.php

For example with thttpd the problem is that SCRIPT_FILENAME is not defined, while PHP absolutely requires it.
My solution corrects that problem !
Flo
11-Feb-2005 04:03
On windows try ctrl-m or ctrl-z to run code in interactive (-a) mode
(*nix ctrl-d)
ken.gregg at rwre dot com
09-Jan-2005 01:38
If you want to use named command line parameters in your script,
the following code will parse command line parameters in the form
of name=value and place them in the $_REQUEST super global array.

cli_test.php
<?php

echo "argv[] = ";
print_r($argv);  // just to see what was passed in

if ($argc > 0)
{
  for (
$i=1;$i < $argc;$i++)
  {
  
parse_str($argv[$i],$tmp);
  
$_REQUEST = array_merge($_REQUEST, $tmp);
  }
}

echo
"\$_REQUEST = ";
print_r($_REQUEST);

?>

rwre:~/tmp$ /usr/local/bin/php cli_test.php foo=1 bar=2 third=a+value

argv[] = Array
(
   [0] => t.php
   [1] => foo=1
   [2] => bar=2
   [3] => third=a+value
)
$_REQUEST = Array
(
   [foo] => 1
   [bar] => 2
   [third] => a value
)
Ben Jenkins
21-Dec-2004 09:23
This took me all day to figure out, so I hope posting it here saves someone some time:
Your PHP-CLI may have a different php.ini than your apache-php.  For example: On my Debian-based system, I discovered I have /etc/php4/apache/php.ini and /etc/php4/cli/php.ini
If you want MySQL support in the CLI, make sure the line
extension=mysql.so
is not commented out.
The differences in php.ini files may also be why some scripts will work when called through a web browser, but will not work when called via the command line.
david at acz dot org
23-Sep-2004 12:46
If you want an interactive command line shell for PHP to test out code, give phpa a try:

http://david.acz.org/phpa/
linn at backendmedia dot com
06-Feb-2004 06:12
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.
ben at slax0rnet dot com
02-Feb-2004 07:34
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

<?php echo "hi!"; ?>
<note, here we would press CTRL-D to parse everything we've entered so far>
hi!
<?php exit(); ?>
<ctrl-d here again>
[root@localhost php-4.3.4]#

I noticed this somehow got ommited from the docs, hope it helps someone!
phprsr at mindtwin dot com
05-Aug-2003 09:12
The basic issue was that PHP-as-CGI REALLY REALLY wants SCRIPT_FILENAME.
It ignores the command line. It ignores SCRIPT_NAME.  It wants
SCRIPT_FILENAME.

"No input file specified."

This very informative error message from PHP means that your web server, WHATEVER it is, is not setting SCRIPT_FILENAME.

The minimum set of env variables:

PATH: DOESN'T MATTER if you're spawning php pages with #!/../php in them
LD_LIBRARY_PATH= should be right
SERVER_SOFTWARE=mini_httpd/1.17beta1 26may2002
SERVER_NAME=who cares
GATEWAY_INTERFACE=CGI/1.1
SERVER_PROTOCOL=HTTP/1.0
SERVER_PORT=whatever
REQUEST_METHOD=GET
SCRIPT_NAME=/foo.php
SCRIPT_FILENAME=/homes/foobie/mini/foo.php    <--- CRITICAL
QUERY_STRING==PHPE9568F35-D428-11d2-A769-00AA001ACF42
REMOTE_ADDR=172.17.12.80
HTTP_REFERER=http://booky16:10000/foo.php
HTTP_USER_AGENT=Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; Q312461; .NET CLR 1.0.3705; .NET CLR 1.1.4322)

If SCRIPT_FILENAME is not set, you'll get the dreaded "No input file specified" message.

mini_httpd does not do this by default. You need to patch it in to make_envp.

A secondary issue is configuration (PHP):

   ./configure --enable-discard-path --with-config-file-path=/homes/wherever/mini/php.ini
  
   (where php.ini is a slightly modified version of php.ini-recommended)
punk [_at_] studionew [_dot_] com
19-Jul-2003 04:18
You can use this function to ask user to enter smth

<?
function read ($length='255')
{
   if (!isset (
$GLOBALS['StdinPointer']))
   {
    
$GLOBALS['StdinPointer'] = fopen ("php://stdin","r");
   }
  
$line = fgets ($GLOBALS['StdinPointer'],$length);
   return
trim ($line);
}

// then

echo "Enter your name: ";
$name = read ();
echo
"\nHello $name! Where you came from? ";
$where = read ();
echo
"\nI see. $where is very good place.";
?>
Adam, php(at)getwebspace.com
17-Jun-2003 04:12
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
monte at ispi dot net
04-Jun-2003 03:47
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.

Monte
Popeye at P-t-B dot com
18-Apr-2003 08:15
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.

example:

# 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.
volkany at celiknet dot com
20-Feb-2003 01:44
Here goes a very simple clrscr function for newbies...
function clrscr() { system("clear"); }
Alexander Plakidin
14-Feb-2003 05:34
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
c dot kelly[no--spam] at qfsaustrlia dot com dot au
06-Feb-2003 08:03
In Windows [NT4.0 sp6a] the example
php -r ' echo getcwd();' does not work ; It appears you have to use the following php -r "echo getcwd();" --not the " around the command  to get the output to screen , just took me half an hour to figure out what was going on.
wanna at stay dot anonynous dot com
22-Jan-2003 09:42
TIP: If you want different versions of the configuration file  depending on what SAPI is used,just name them php.ini (apache module), php-cli.ini (CLI) and php-cgi.ini (CGI) and dump them all in the regular configuration directory. I.e no need to compile several versions of php anymore!
phpnotes at ssilk dot de
22-Oct-2002 03:36
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.
justin at visunet dot ie
21-Oct-2002 09:21
If you are trying to set up an interactive command line script and you want to get started straight away (works on 4+ I hope). Here is some code to start you off:

<?php

  
// Stop the script giving time out errors..
  
set_time_limit(0);

  
// This opens standard in ready for interactive input..
  
define('STDIN',fopen("php://stdin","r"));

  
// Main event loop to capture top level command..
  
while(!0)
   {
      
      
// Print out main menu..
      
echo "Select an option..\n\n";
       echo
"    1) Do this\n";
       echo
"    2) Do this\n";
       echo
"    3) Do this\n";
       echo
"    x) Exit\n";

      
// Decide what menu option to select based on input..
      
switch(trim(fgets(STDIN,256)))
       {
           case
1:
               break;
              
           case
2:
               break;

           case
3:
               break;

           case
"x":
               exit();
              
           default:
               break;
       }

   }

  
// Close standard in..
  
fclose(STDIN);

?>
phpNOSPAM at dogpoop dot cjb dot net
11-Oct-2002 08:28
Here are some instructions on how to make PHP files executable from the command prompt in Win2k.  I have not tested this in any other version of Windows, but I'm assuming it will work in XP, but not 9x/Me.

There is an environment variable (control panel->system->advanced->environment variables) named PATHEXT.  This is a list of file extensions Windows will recognize as executable at the command prompt.  Add .PHP (or .PL, or .CLASS, or whatever) to this list.  Windows will use the default action associated with that file type when you execute it from the command prompt.

To set up the default action:
Open Explorer.
Go to Tools->folder options->file types
Find the extension you're looking for.  If it's not there, click New to add it.
Click on the file type, then on Advanced, then New.
For the action, type "Run" or "Execute" or whatever makes sense.
For the application, type
  {path to application} "%1" %*
The %* will send any command line options that you type to the program.
The application field for PHP might look like
  c:\php\php.exe -f "%1" -- %*
(Note, you'll probably want to use the command line interface version php-cli.exe)
or for Java
  c:\java\java.exe "%1" %*
Click OK.
Click on the action that was just added, then click Set default.

If this helps you or if you have any changes/more information I would appreciate a note.  Just remove NOSPAM from the email address.
jeff at noSpam[] dot genhex dot net
06-Sep-2002 05:13
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.
zager[..A..T..]teleaction.de
15-Aug-2002 11:15
Under Solaris (at least 2.6) I have some problems with reading stdin. Original pbms report may be found here:
http://groups.google.com/groups?
q=Re:+%5BPHP%5D+Q+on+php://stdin+--+an+answer!&hl=en&lr=&ie=UTF-
8&oe=UTF-8&selm=3C74AF57.6090704%40Sun.COM&rnum=1

At a first glance the only solution for it is 'fgetcsv'

#!/usr/local/bin/php -q
<?php

set_magic_quotes_runtime
(0);
$fd=fopen("php://stdin","r");
if (!
$fd)
  exit;

while (!
feof ($fd))
{
 
$s = fgetcsv($fd,128,"\n");
  if (
$s==false)
   continue;

  echo
$s[0]."\n";
}
?> 

But... keep reading....

>>> I wrote
Hello,
Sometimes I hate PHP... ;)

Right today I was trapped by some strange bug in my code with reading stdin using fgetcsv.
After a not small investigation I found that strings like "foo\nboo\ndoo"goo\n (take note of double quatation sign in it)
interpreted by fgetcsv like:
1->foo\nboo\ndoo
2->goo
since double quotation mark has a special meaning and get stripped off of the input stream.
Indeed, according to PHP manual:
[quote]
array fgetcsv ( int fp, int length [, string delimiter [, string enclosure]])

[skip]
another delimiter with the optional third parameter. _The_enclosure_character_is_double_quote_,_unless_
it_is_specified_.
[skip]
_enclosure_is_added_from_PHP 4.3.0.      !!!!!!
[/quote]

Means no chance for us prior to 4.3.0 :(
But file() works just fine !!!! Of course by the price of memory, so be careful with large files.

set_magic_quotes_runtime(0); // important, do not forget it !!!
$s=file("php://stdin");
for ($i=0,$n=sizeof($s);$i<$n;$i++)
{
  do_something_useful(rtrim($s[$i]));
}

Conclusion:
1. If you have no double quotation mark in your data use fgetcsv
2. From 4.3.0 use  fgetcsv($fd,"\n",""); // I hope it will help
3. If you data is not huge use file("php://stdin");

Hope now it's cleared for 100% (to myself ;)

Good luck!
Dim

PS. Don't forget that it's only Solaris specific problem. Under Linux just use usual fgets()...
jonNO at SPAMjellybob dot co dot uk
03-Aug-2002 09:17
If you want to get the output of a command use the function shell_exec($command) - it returns a string with the output of the command.
ben-php dot net at wefros dot com
13-Jun-2002 03:40
PHP 4.3 and above automatically have STDOUT, STDIN, and STDERR openned ... but < 4.3.0 do not.  This is how you make code that will work in versions previous to PHP 4.3 and future versions without any changes:

<?php
  
if (version_compare(phpversion(),'4.3.0','<')) {
      
define('STDIN',fopen("php://stdin","r"));
      
define('STDOUT',fopen("php://stout","r"));
      
define('STDERR',fopen("php://sterr","r"));
      
register_shutdown_function( create_function( '' , 'fclose(STDIN); fclose(STDOUT); fclose(STDERR); return true;' ) );
   }

/* get some STDIN up to 256 bytes */
  
$str = fgets(STDIN,256);
?>
pyxl at jerrell dot com
18-Feb-2002 11:52
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.

<Ограниченные или недоступные в защищенном режиме функцииСправочник функций>
 Last updated: Tue, 15 Nov 2005