I append this to most of my PHP files, to allow command line unit testing of a class. It ensures that the unit test is only run if the script is run directly, and won't be triggered by an include from another CLI script.
<?php
if (!empty($argc) && strstr($argv[0], basename(__FILE__))) {
$test = new TestClass();
$rv = $test->Test();
die("Test returned $rv\n");
}
?>
명령줄에서 PHP 사용하기
버전 4.3.0부터 PHP는 Command Line Interface를 의미하는 CLI라는 이름의 새로운 SAPI(Server Application Programming Interface) 형식을 지원한다. 이 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가 활성화되어있다. 그리고 --disable-cli로 비활성화시킬수 있다.
PHP 4.3.0부터, CLI/CGI 바이너리의 이름과 위치, 존재여부는 PHP가 시스템에 어떻게 설치되느냐에 따라 달라질 것이다. 기본값으로 make를 수행할때, CGI와 CLI 모두 빌드되고 각각 sapi/cgi/php와 sapi/cli/php에 위치하게 된다. 둘 다 php라는 이름이 붙는다는것에 주의해야 할것이다. configure 줄에 따라 make install 시에 무슨일이 일어날까. configure 시에 모듈로 SAPI를 선택했다면, 즉 apxs를 사용하거나, 또는 --disable-cgi 옵션을 사용하면 CLI는 make install시에 {PREFIX}/bin/php에 복사된다. 예를 들면, --with-apxs가 configure 줄에 포함되면 make install시에 CLI는 {PREFIX}/bin/php에 복사된다. CGI 바이너리 설치를 오버라이드하고 싶다면 make install 이후에 make install-cli를 사용한다. 차선책으로 configure 줄에 --disable-cgi를 설정할수 있다.
Note: --enable-cli와 --enable-cgi는 모두 기본값으로 켜져 있기 때문에, 단순히 configure줄에 --enable-cli를 넣는것이 make install시에 {PREFIX}/bin/php에 CLI를 복사할것이라는 것을 의미하지 않는다.
PHP 4.2.0 과 PHP 4.2.3 사이의 윈도우 패키지는 CLI를 php-cli.exe로 제공한다. CGI인 php.exe와 같은 폴더에 존재한다. PHP 4.3.0부터 윈도우 패키지 배포판은 CLI를 별개의 폴더 cli에 php.exe를 놓으므로, cli/php.exe가 됩니다. PHP 5부터, CLI는 메인 폴더에 php.exe로 배포됩니다. CGI 버전은 php-cgi.exe로 배포됩니다.
PHP 5부터, 새로운 php-win.exe 파일이 배포됩니다. 이는 CLI 버전과 동일하지만, php-win은 아무것도 출력하지 않으므로, 콘솔을 제공하지 않습니다. (화면에 "도스 박스"가 나타나지 않습니다) 이 동작은 php-gtk와 비슷합니다. --enable-cli-win32로 configure해야 합니다.
Note: 현재 사용중인 SAPI는 무엇인가?
셀에서, php -v를 쳐넣으면 php가 CGI인지 CLI인지 알수 있을것이다. php_sapi_name()과 상수PHP_SAPI도 참고.
Note: PHP 4.3.2에서 유닉스 manual 페이지가 추가되었다. 셀 환경에서 man php를 침으로써 이 페이지를 볼수 있을것이다.
다른 SAPI와 비교한 CLI SAPI의 현저한 차이점:
-
CGI SAPI와는 달리, 출력에 헤더를 쓰지 않는다.
CGI SAPI가 HTTP 헤더를 제거하는 방법을 제공하지만, CLI SAPI에서는 헤더를 활성화시킬수 있는 스위치가 존재하지 않는다.
CLI는 기본적으로 정숙 모드로 시작된다. 그러나 구버전의 CGI 스크립트와의 호환성을 위해 -q 스위치를 유지하고 있다.
작업 디렉토리가 스크립트의 디렉토리로 변경되지 않는다 (-C와 --no-chdir 스위치는 호환성을 유지됩니다)
일반 텍스트 에러 메시지 (HTML 포맷이 아님)
-
셀 환경에 맞지 않는 것들 때문에 CLI SAPI에 의해 오버로드되는 php.ini 지시어가 몇가지 존재한다.
php.ini 지시어 오버로드 지시어 CLI SAPI 기본값 주석 html_errors FALSE 셀에서 에러메시지를 읽을때 의미없는 HTML태그로 뒤범벅이 되면 에러메시지를 읽기가 매우 어려울수 있다. 따라서 이 지시어의 기본값은 FALSE다. implicit_flush TRUE print(), echo() 와 비슷한 함수들의 출력은 모두 즉시 출력으로 쓰기 되고 버퍼에 캐시되지 않는다. 표준 출력을 지연시키거나 조작하고 싶다면 output buffering을 사용할수도 있다. max_execution_time 0 (무제한) 셀 환경에서 PHP를 무한하게 사용할 가능성때문에, 최대 실행 시간은 무제한으로 설정된다. 웹 응용프로그램은 대부분 매우 빨리 실행이 끝나는 반면에 셀 응용프로그램은 더 많은 시간이 필요한 경우가 많다. register_argc_argv TRUE 이 설정은 TRUE이기 때문에 CLI SAPI에서는 항상 argc (응용프로그램에 전달되는 인수의 수) 와 argv (응용프로그램에 전단되는 인수의 배열)을 사용할수 있을것이다.
PHP 4.3.0부터, CLI SAPI는 PHP 변수 $argc와 $argv가 등록되고 적절한 값으로 채워지게 된다. 이 변수의 생성은 CGI와 MODULE 버전과 같이 register_globals가 on되어 있어야 한다. 버전이나 register_globals의 설정에 관계없이, $_SERVER나 $HTTP_SERVER_VARS로 그 값에 접근할수 있다. Example: $_SERVER['argv']
Note: 이 지시어는 설정 파일 php.ini나 사용자 설정으로부터 온 다른 값으로 초기화될수 없다. 모든 설정 파일이 해석되고 난 후에 기본값이 적용되기 때문에 이 것은 제한이 된다. 하지만, 각 값은 런타임동안에 변경될수 있다. (위 지시어 중 환경과 맞지 않는것 e.g. register_argc_argv).
-
셀 환경에서의 작업을 편하게 하기 위해, 다음 상수가 정의되었다:
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에 의해 자동적으로 닫히기 때문이다.
Note: 이 상수들은 PHP 스크립트를 stdin에서 읽을 경우에는 사용할 수 없습니다.
-
CLI SAPI는 현재 디렉토리를 실행중인 스크립트의 디렉토리로 변경 하지않는다!
다음예는 CGI SAPI와의 차이점을 보여준다:
<?php
// Our simple test application named 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에서 셀 툴을 제작할때 좀더 많은 유연성을 허용한다.
Note: CGI SAPI 는 명령줄에서 실행할때 -C 스위치를 사용하여 CLI SAPI의 동작을 지원한다.
PHP 바이너리에 의해 제공되는 명령줄 옵션의 리스트는 PHP를 -h 스위치와 함께 실행하므로써 어느때든 질의를 할수 있다.
Usage: php [options] [-f] <file> [--] [args...]
php [options] -r <code> [--] [args...]
php [options] [-B <begin_code>] -R <code> [-E <end_code>] [--] [args...]
php [options] [-B <begin_code>] -F <file> [-E <end_code>] [--] [args...]
php [options] -- [args...]
php [options] -a
-a Run interactively
-c <path>|<file> Look for php.ini file in this directory
-n No php.ini file will be used
-d foo[=bar] Define INI entry foo with value 'bar'
-e Generate extended information for debugger/profiler
-f <file> Parse and execute <file>.
-h This help
-i PHP information
-l Syntax check only (lint)
-m Show compiled in modules
-r <code> Run PHP <code> without using script tags <?..?>
-B <begin_code> Run PHP <begin_code> before processing input lines
-R <code> Run PHP <code> for every input line
-F <file> Parse and execute <file> for every input line
-B <begin_code> Run PHP <end_code> after processing all input lines
-H Hide any passed arguments from external tools.
-s Display colour syntax highlighted source.
-v Version number
-w Display source with stripped comments and whitespace.
-z <file> Load Zend extension <file>.
args... Arguments passed to script. Use -- args when first argument
starts with - or script is read from stdin
--ini Show configuration file names
--rf <name> Show information about function <name>.
--rc <name> Show information about class <name>.
--re <name> Show information about extension <name>.
--ri <name> Show configuration for extension <name>.
CLI SAPI는 실행하고자 하는 PHP 코드를 취하는 3가지의 방법을 사용한다.
-
PHP에게 특정 파일을 실행하도록 지정함.
php my_script.php php -f my_script.php
두 방법 (-f 스위치를 사용하거나 안하는것)은 모두 my_script.php을 실행한다. 실행하고자하는 파일을 선택할수 있다 - PHP 스크립트는 .php 확장자 로 끝날필요없이 어떤 이름이나 원하는 확장자를 갖을수 있다.
Note: 스크립트에 인수를 전달해야 할 때, -f 스위치를 사용할 경우 --을 첫번째 인수로 전달해야 합니다.
-
명령줄에서 실행하고자 하는 PHP 코드를 직접 전달함.
php -r 'print_r(get_defined_constants());'
셀 변수 변환과 따옴표 사용에 있어서 특별한 주의가 필요하다.
Note: 예제 코드를 주의깊게 읽으면, 시작과 끝 태그가 존재하지 않는다! -r 스위치는 그 태그들이 필요하지 않다. 그 태그들을 사용하면 해석 에러가 발생할것이다.
-
표준 입력(stdin)을 통해 수행되는 PHP 코드를 제공함
이 방식은 동적인 PHP 코드를 생성할수 있는 강력한 기능을 부여하고 바이너리에 그 코드를 넘겨준다. 다음 (가상의) 예제코드에서 보여주는 바와 같다.
$ some_application | some_filter | php | sort -u >final_output.txt
코드를 수행하기 위한 세 가지 방법의 어떤것도 조합할수 없다.
모든 셀 응용 프로그램처럼, PHP 바이너리는 많은수의 인수를 허용하고 PHP 스크립트도 인수를 받을수 있다. 스크립트로 전달할수 있는 인수의 갯수는 PHP에 의해 제한받지 않는다. (셀은 전달할수 있는 문자 갯수의 제한을 갖는다; 보통 이 제한을 넘지 않을것이다) 스크립트로 전달할수 있는 인수는 전역 배열 $argv에 존재한다. 제로 인덱스는 항상 스크립트 명을 포함한다 (PHP 코드가 표준 입력이나 명령줄 스위치 -r로부터 온 경우에는 - ). 두번째로 등록된 전역 변수는 $argv배열의 구성요소 수를 갖는 $argc이다 (스크립트로 전달되는 인수의 수가 아니다)
스크립트로 전달하려는 인수가 -문자로 시작되지 않는한, 특별하게 조심할 필요는 없다. -로 시작하는 인수를 스크립트에 전달하면 문제가 발생할 소지가 있다 왜냐하면 PHP는 그 인수를 PHP가 제어해야 한다고 생각하기 때문이다. 이런일이 발생하지 않기 위해서는, -- 구분자의 인수 리스트를 사용한다. 이 구분자가 PHP에 의해 해석된 후에, 그 뒤의 모든 인수가 스크립트로 온전히 전달된다.
# This will not execute the given code but will show the PHP usage
$ php -r 'var_dump($argv);' -h
Usage: php [options] [-f] <file> [args...]
[...]
# This will pass the '-h' argument to your script and prevent PHP from showing it's usage
$ php -r 'var_dump($argv);' -- -h
array(2) {
[0]=>
string(1) "-"
[1]=>
string(2) "-h"
}
하지만, 셀 스크립트에서 PHP를 사용하는 다른 방법이 있다. 첫번째 줄을 #!/usr/bin/php로 시작하는 스크립트를 작성할수 있다. 이 줄 뒤에는 PHP의 시작과 끝 태그 안에 포함된 일반적인 PHP 코드를 놓을수 있다. 이 파일에 적절하게 실행 속성을 설정하면 (e.g. chmod +x test) 스크립트는 보통의 셀이나 펄 스크립트처럼 실행될수 있다:
Example #1 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부터 사용할 수 있습니다.
| 옵션 | 긴 옵션 | 설명 |
|---|---|---|
| -a | --interactive |
PHP를 대화적으로 실행합니다. PHP를 Readline 확장과 함께 컴파일했다면(윈도우에서는 불가능), 자동 완성 기능(예. 변수명의 시작 부분을 치고 TAB을 누르면 PHP가 이름을 완성해줍니다)과 화살표 키로 사용할 수 있는 타이핑 기록을 가진 멋진 쉘을 가지게 됩니다. 기록은 ~/.php_history 파일에 저장됩니다.
|
| -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] 예제 (표시 관계로 줄바꿈을 하였습니다):
# Omitting the value part will set the given configuration directive to "1"
$ php -d max_execution_time
-r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(1) "1"
# Passing an empty value part will set the configuration directive to ""
php -d max_execution_time=
-r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(0) ""
# The configuration directive will be set to anything passed after the '=' character
$ 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"
|
| -e | --profile-info |
디버거/프로파일러에서 사용할 수 있는 확장 정보 모드를 켭니다. |
| -f | --file |
-f 옵션으로 주어진 파일명을 해석하여 실행합니다. 이 스위치는 선택적으로 생략할 수 있습니다. 단지 실행할 파일명만 제공해도 됩니다.
|
| -h 와 -? | --help 와 --usage | 이 옵션으로, 실제 명령줄 옵션 목록과 작동에 관한 한 줄 설명에 대한 정보를 얻을 수 있습니다. |
| -i | --info | 이 명령줄 옵션은 phpinfo()를 호출하여, 그 결과를 출력합니다. PHP가 제대로 작동하지 않으면, php -i를 사용하여 어떠한 오류 메세지가 시작시나 정보표에 나오는지 확인할 수 있습니다. CGI 모드를 사용하면 출력은 HTML이고 매우 큰 점에 주의하십시오. |
| -l | --syntax-check |
이 옵션은 주어진 PHP 코드의 문법 검사만 수행하게 하는 편리한 방법을 제공함. 성공하면, No syntax errors detected in <filename>라는 메시지가 표준 출력으로 쓰여지고 셀의 리턴 코드는 0이다. 실패하면, 내부적인 해석기 에러와 함께 Errors parsing <filename>라는 메시지가 표준 출력으로 쓰여지고 셀의 리턴 코드는 -1이 된다. 이 옵션은 치명적인 에러를 발견할수 없을것이다 (undefined functions 같은). -f 옵션을 사용하면 치명적인 에러도 함께 찾을수 있을것이다.
|
| -m | --modules |
이 옵션을 사용하여, PHP는 내장(로드된)된 PHP 모듈과 Zend 모듈을 출력한다. $ php -m [PHP Modules] xml tokenizer standard session posix pcre overload mysql mbstring ctype [Zend Modules] |
| -r | --run |
이 옵션은 명령줄에서 직접 PHP를 수행하도록 해줌. PHP의 시작과 끝 태그 (<?php 과 ?>)는 필요하지 않다. 만약 존재한다면 해석 에러가 발생할것이다.
|
| -B | --process-begin |
stdin을 처리하기 전에 실행할 PHP 코드. PHP 5에서 추가. |
| -R | --process-code |
매 입력줄마다 실행할 PHP 코드. PHP 5에서 추가. 이 모드에서 사용할 수 있는 두가지 특별한 변수가 있습니다: $argn과 $argi. $argn은 현 시점에서 PHP가 처리하는 줄을 가지고, $argi은 줄 번호를 가집니다. |
| -F | --process-file |
매 입력줄마다 실행할 PHP 파일. PHP 5에서 추가. |
| -E | --process-end |
입력을 처리한 후에 실행할 PHP 코드. PHP 5에서 추가. Example #2 프로젝트 줄 수를 세기 위해 -B, -R, -E 옵션 사용하기. $ find my_proj | php -B '$l=0;' -R '$l += count(@file($argn));' -E 'echo "Total Lines: $l\n";' Total Lines: 37328 |
| -s | --syntax-highlight 와 --syntax-highlighting |
색으로 구문을 강조한 소스를 표시합니다. 이 옵션은 파일을 해석하는 내부 메커니즘을 사용하여 강조된 HTML 버전을 생성하여 표준 출력에 씁니다. 이로써 만들어지는 것은 HTML <code> [...] </code> 태그 블럭만이고, HTML 헤더는 출력하지 않습니다.
|
| -v | --version |
PHP, PHP SAPI, 젠드 버전을 표준 출력으로 씁니다. 예를 들면, $ 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 |
| -w | --strip |
주석과 공백을 제거한 소스를 표시합니다.
|
| -z | --zend-extension |
젠드 확장을 적재합니다. 파일명만 주어지면, PHP는 시스템의 기본 라이브러리 경로(보통 리눅스 시스템에서 /etc/ld.so.conf로 지정)에서 확장을 적재하려고 시도합니다. 절대 경로 정보와 파일명을 넘겨주면 시스템 라이브러리 검색 경로를 사용하지 않습니다. 디렉토리 정보와 함께 상대적인 파일명을 사용하면 PHP는 현재 디렉토리에서 상대적인 경로에서만 확장 적재를 시도합니다. |
| --ini |
설정 파일명과 검색한 디렉토리를 표시합니다. PHP 5.2.3부터 사용할 수 있습니다. Example #3 --ini 예제 $ php --ini Configuration File (php.ini) Path: /usr/dev/php/5.2/lib Loaded Configuration File: /usr/dev/php/5.2/lib/php.ini Scan for additional .ini files in: (none) Additional .ini files parsed: (none)
|
|
| --rf | --rfunction |
주어진 함수나 클래스 메쏘드에 대한 정보(예. 인수의 갯수와 이름)를 보여줍니다. PHP 5.1.2부터 사용할 수 있습니다. 이 옵션은 PHP를 Reflection과 함께 컴파일했을 경우에만 사용할 수 있습니다.
Example #4 기본 --rf 사용법 $ php --rf var_dump
Function [ <internal> public function var_dump ] {
- Parameters [2] {
Parameter #0 [ <required> $var ]
Parameter #1 [ <optional> $... ]
}
}
|
| --rc | --rclass |
주어진 클래스에 대한 정보(상수, 프로퍼티, 메쏘드의 목록)를 보여줍니다. PHP 5.1.2부터 사용할 수 있습니다. 이 옵션은 PHP를 Reflection과 함께 컴파일했을 경우에만 사용할 수 있습니다.
Example #5 --rc 예제 $ php --rc Directory
Class [ <internal:standard> class Directory ] {
- Constants [0] {
}
- Static properties [0] {
}
- Static methods [0] {
}
- Properties [0] {
}
- Methods [3] {
Method [ <internal> public method close ] {
}
Method [ <internal> public method rewind ] {
}
Method [ <internal> public method read ] {
}
}
}
|
| --re | --rextension |
주어진 확장에 대한 정보(php.ini 옵션, 정의된 함수, 상수, 클래스의 목록)를 보여줍니다. PHP 5.1.2부터 사용할 수 있습니다. 이 옵션은 PHP를 Reflection과 함께 컴파일했을 경우에만 사용할 수 있습니다.
Example #6 --re 예제 $ php --re json
Extension [ <persistent> extension #19 json version 1.2.1 ] {
- Functions {
Function [ <internal> function json_encode ] {
}
Function [ <internal> function json_decode ] {
}
}
}
|
| --ri | --rextinfo |
주어진 확장의 설정 정보(phpinfo()의 반환 정보와 동일)를 보여줍니다. PHP 5.2.2부터 사용할 수 있습니다. 핵심 설정 정보는 확장 이름으로 "main"을 사용해서 확인할 수 있습니다.
Example #7 --ri 예제 $ php --ri date date date/time support => enabled "Olson" Timezone Database Version => 2007.5 Timezone Database => internal Default timezone => Europe/Oslo Directive => Local Value => Master Value date.timezone => Europe/Oslo => Europe/Oslo date.default_latitude => 59.22482 => 59.22482 date.default_longitude => 11.018084 => 11.018084 date.sunset_zenith => 90.583333 => 90.583333 date.sunrise_zenith => 90.583333 => 90.583333
|
PHP 실행 파일은 웹서버와 절대적으로 독립적인 PHP 스크립트를 실행하기 위해 사용될수 있다. 유닉스 시스템에 있다면, PHP 스크립트의 첫번째 줄에 특별한 것을 추가해야 하고, 실행가능하게 해서, 무슨 프로그램이 스크립트를 수행시킬지 시스템이 알수 있도록 한다. 윈도우 플랫폼에서는 .php파일의 더블 클릭 옵션을 갖는 php.exe와 연관시킬수 있거나, PHP를 통해 그 스크립트를 수행하도록 배치 파일을 만들수 있다. 유닉스에서 실행시키기위해 추가된 첫번째 줄은 윈도우에 아무런 해가 없을것이다. 그래서 이 방법을 사용하여 플랫폼 프로그램을 번갈아 작성할수 있다. 명령줄 PHP 프로그램을 작성하는 단순한 에제 코드를 아래에서 볼수 있다.
Example #8 명령줄에서 실행되도록 의도된 스크립트(script.php)
<?php
if ($argc != 2 || in_array($argv[1], array('--help', '-help', '-h', '-?'))) {
?>
This is a command line PHP script with one option.
Usage:
<?php echo $argv[0]; ?> <option>
<option> can be some word you would like
to print out. With the --help, -help, -h,
or -? options, you can get this help.
<?php
} else {
echo $argv[1];
}
?>
위 스크립트에서, 특별한 첫번째 줄을 사용하여 이 파일이 PHP에 의해 실행되어야 한다는 것을 가리킨다. CLI 버전을 사용한다면, HTTP 헤더가 존재하지 않을것이다. PHP 의 커맨드라인 응용프로그램을 작성할때 사용할수 있는 두개의 변수가 존재한다:$argc와 $argv. 첫번째 변수는 인수 갯수에 하나(스크립트명)가 추가된 값이다. 두번째 변수는 인수들를 포함하는 배열인데, 이 배열은 제로 ($argv[0])에 스크립트명을 갖으면 시작된다.
위 프로그램에서는 인수가 하나 이하인가 이상인가를 체크한다. 인수가 --help나, -help, -h, -?이면, help 메시지를 출력하고, 스크립트명을 동적으로 출력한다. 다른 인수를 받게 되면, 그 인수를 출력한다.
유닉스에서 위 스크립트를 수행하려 하면, 그 파일을 실행가능하게 해서 단순히 script.php echothis나 script.php -h를 호출하면 된다. 윈도우에서는, 이 작업을 위해 배치 파일을 만들수 있다.
Example #9 명령줄의 PHP 스크립트를 수행하기 위한 배치 파일(script.bat)
@C:\php\php.exe script.php %1 %2 %3 %4
위 프로그램이 script.php이란 이름을 갖고, C:\php\php.exe 안에 CLI php.exe를 갖는다면 이 배치 파일은 추가된 옵션과 함께 실행이 될것이다: script.bat echothis나 script.bat -h.
PHP의 명령줄 응용 프로그램의 기능을 확장하기 위한 좀더 많은 함수를 보기위해 Readline 확장에 대한 문서도 참고한다.
명령줄에서 PHP 사용하기
09-Oct-2009 01:06
11-Sep-2009 10:34
Use PHP as Scripting Language in Windows Vista and 7:
ASSOC .phs=PHPScript
FTPYE PHPScript=[path to]\php.exe -f "%1" -- %*
optional set PATHEXT=.phs;%PATHEXT%
now you can execute any php-script (ext: .phs) from the shell like a .vbs or .cmd.
"c:\testscript.phs arg1 arg2" or with the optional step "c:\testscript arg1 arg2"
i hope this helps somebody.
07-Sep-2009 07:46
I've just found that the fact that the CLI does *not* change the current directory will make include() and require() calls with relative paths fail. This is because they are relative to the current directory, not to the current executing file, the documentation notwithstanding. In CGI mode, this is the same because it changes the current directory.
One solution is to call the CGI binary rather than the CLI one. A better solutions is to use dirname(__FILE__) in your path names.
30-Aug-2009 06:30
To detect if run from CLI:
if (defined('STDIN'))
or:
if (isset($argc))
22-Aug-2009 08:59
This command line option parser supports any combination of three types of options (switches, flags and arguments) and returns a simple array.
[pfisher ~]$ php test.php --foo --bar=baz
["foo"] => true
["bar"] => "baz"
[pfisher ~]$ php test.php -abc
["a"] => true
["b"] => true
["c"] => true
[pfisher ~]$ php test.php arg1 arg2 arg3
[0] => "arg1"
[1] => "arg2"
[2] => "arg3"
<?php
function parseArgs($argv){
array_shift($argv);
$out = array();
foreach ($argv as $arg){
if (substr($arg,0,2) == '--'){
$eqPos = strpos($arg,'=');
if ($eqPos === false){
$key = substr($arg,2);
$out[$key] = isset($out[$key]) ? $out[$key] : true;
} else {
$key = substr($arg,2,$eqPos-2);
$out[$key] = substr($arg,$eqPos+1);
}
} else if (substr($arg,0,1) == '-'){
if (substr($arg,2,1) == '='){
$key = substr($arg,1,1);
$out[$key] = substr($arg,3);
} else {
$chars = str_split(substr($arg,1));
foreach ($chars as $char){
$key = $char;
$out[$key] = isset($out[$key]) ? $out[$key] : true;
}
}
} else {
$out[] = $arg;
}
}
return $out;
}
?>
Full version with comments here: http://pwfisher.com/nucleus/index.php?itemid=45
07-Jun-2009 02:06
In the notes it there is an example of running 1 line of PHP using:
php -r 'print_r(get_defined_constants());'
This might work on a UNIX machine but unfortunately on windows it produces the following error message:
Parse error: parse error in Command line code on line 1
Instead of using ' (single quotes) to encompass the PHP code use " (double quotes) instead. You can safely use ' within the code itself however such as:
php -r "echo 'hello';"
07-May-2009 06:23
Notice that piping output to some programs will have unexpected behavior:
php my_script.php | less
The 'less' program usually sets the terminal mode so pressing ENTER is not necessary. When using php-cli, it is necessary to press ENTER, unless "!stty sane" is able to fix things for you. The php command is doing something to the terminal mode despite no interactive shell being requested.
24-Feb-2009 11:11
I'm figuring out how to pipe an email to a php script with postfix. For the email user@example.com:
I created the following line in /etc/aliases:
user: "|/www/file.php"
file.php is chmod 755
This works fine. But I wanted to test this without having to send an email every time. And this took some searching to figure out, yet it's oh-so simple:
To pipe the file email.txt to the script, write the following in the terminal window:
user@host: php file.php < testepost.txt
I was confused by the | in the aliases file, and didn't get what came after what, etc etc.
Regards,
Willy T. Koch
Norway
11-Nov-2008 04:43
For command-line option definition and parsing, don't forget about the beauty of getopt().
There's a php-native version (http://php.net/getopt) and a PEAR package -- Console_GetOpt (http://pear.php.net/package/Console_Getopt).
26-Oct-2008 05:52
Here's my modification of "thomas dot harding at laposte dot net" script (below) to read arguments from $argv of the form --name=VALUE and -flag.
"Input":
./script.php -a arg1 --opt1 arg2 -bcde --opt2=val2 arg3 arg4 arg5 -fg --opt3
"print_r Output":
Array
(
[exec] => ./script.php
[options] => Array
(
[0] => opt1
[1] => Array
(
[0] => opt2
[1] => val2
)
[2] => opt3
)
[flags] => Array
(
[0] => a
[1] => b
[2] => c
[3] => d
[4] => e
[5] => f
[6] => g
)
[arguments] => Array
(
[0] => arg1
[1] => arg2
[2] => arg3
[3] => arg4
[4] => arg5
)
)
<?php
function arguments($args ) {
$ret = array(
'exec' => '',
'options' => array(),
'flags' => array(),
'arguments' => array(),
);
$ret['exec'] = array_shift( $args );
while (($arg = array_shift($args)) != NULL) {
// Is it a option? (prefixed with --)
if ( substr($arg, 0, 2) === '--' ) {
$option = substr($arg, 2);
// is it the syntax '--option=argument'?
if (strpos($option,'=') !== FALSE)
array_push( $ret['options'], explode('=', $option, 2) );
else
array_push( $ret['options'], $option );
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
$ret['arguments'][] = $arg;
continue;
}
return $ret;
}//function arguments
?>
04-Oct-2008 02:27
To allow a "zero" option value:
replace:
$ret['options'][$com] = !empty($value) ? $value : true;
by:
$ret['options'][$com] = (strlen($value) > 0 ? $value : true);
In the sample below.
Thanks to Chris Chubb to point me out the problem
15-Jun-2008 12:08
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
<?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("=",$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;
}
if (!count($ret['options']) && !count($ret['flags']))
{
$ret['arguments'] = array_merge($ret['commands'], $ret['arguments']);
$ret['commands'] = array();
}
return $ret;
}
exit (0)
/* vim: set expandtab tabstop=2 shiftwidth=2: */
?>
07-May-2008 10:08
If a module SAPI is chosen during configure, such as apxs, or the --disable-cgi option is used, the CLI is copied to {PREFIX}/bin/php during make install otherwise the CGI is placed there.
versus
Changed CGI install target to php-cgi and 'make install' to install CLI when CGI is selected. (changelog for 5.2.3)
http://www.php.net/ChangeLog-5.php#5.2.3
29-Feb-2008 03:32
When you want to get inputs from STDIN, you may use this function if you like using C coding style.
<?php
// up to 8 variables
function scanf($format, &$a0=NULL, &$a1=NULL, &$a2=NULL, &$a3=NULL,
&$a4=NULL, &$a5=NULL, &$a6=NULL, &$a7=NULL)
{
$num_args = func_num_args();
if($num_args > 1) {
$inputs = fscanf(STDIN, $format);
for($i=0; $i<$num_args-1; $i++) {
$arg = 'a'.$i;
$$arg = $inputs[$i];
}
}
}
scanf("%d", $number);
?>
17-Feb-2008 06:29
I find regex and manually breaking up the arguments instead of havingon $_SERVER['argv'] to do it more flexiable this way.
cli_test.php asdf asdf --help --dest=/var/ -asd -h --option mew arf moo -z
Array
(
[input] => Array
(
[0] => asdf
[1] => asdf
)
[commands] => Array
(
[help] => 1
[dest] => /var/
[option] => mew arf moo
)
[flags] => Array
(
[0] => asd
[1] => h
[2] => z
)
)
<?php
function arguments ( $args )
{
array_shift( $args );
$args = join( $args, ' ' );
preg_match_all('/ (--\w+ (?:[= ] [^-]+ [^\s-] )? ) | (-\w+) | (\w+) /x', $args, $match );
$args = array_shift( $match );
/*
Array
(
[0] => asdf
[1] => asdf
[2] => --help
[3] => --dest=/var/
[4] => -asd
[5] => -h
[6] => --option mew arf moo
[7] => -z
)
*/
$ret = array(
'input' => array(),
'commands' => array(),
'flags' => array()
);
foreach ( $args as $arg ) {
// Is it a command? (prefixed with --)
if ( substr( $arg, 0, 2 ) === '--' ) {
$value = preg_split( '/[= ]/', $arg, 2 );
$com = substr( array_shift($value), 2 );
$value = join($value);
$ret['commands'][$com] = !empty($value) ? $value : true;
continue;
}
// Is it a flag? (prefixed with -)
if ( substr( $arg, 0, 1 ) === '-' ) {
$ret['flags'][] = substr( $arg, 1 );
continue;
}
$ret['input'][] = $arg;
continue;
}
return $ret;
}
print_r( arguments( $argv ) );
?>
12-Feb-2008 03:21
Here's an update to the script a couple of people gave below to read arguments from $argv of the form --name=VALUE and -flag. Changes include:
Don't use $_ARG - $_ is generally considered reserved for the engine.
Don't use regex where a string operation will do just as nicely
Don't overwrite --name=VALUE with -flag when 'name' and 'flag' are the same thing
Allow for VALUE that has an equals sign in it
<?php
function arguments($argv) {
$ARG = array();
foreach ($argv as $arg) {
if (strpos($arg, '--') === 0) {
$compspec = explode('=', $arg);
$key = str_replace('--', '', array_shift($compspec));
$value = join('=', $compspec);
$ARG[$key] = $value;
} elseif (strpos($arg, '-') === 0) {
$key = str_replace('-', '', $arg);
if (!isset($ARG[$key])) $ARG[$key] = true;
}
}
return $ARG;
}
?>
29-Oct-2007 12:51
Here's <losbrutos at free dot fr> function modified to support unix like param syntax like <B Crawford> mentions:
<?php
function arguments($argv) {
$_ARG = array();
foreach ($argv as $arg) {
if (preg_match('#^-{1,2}([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];
}
/* make unix like -afd == -a -f -d */
if(preg_match("/^-([a-zA-Z0-9]+)/", $matches[0], $match)) {
$string = $match[1];
for($i=0; strlen($string) > $i; $i++) {
$_ARG[$string[$i]] = true;
}
} else {
$_ARG[$key] = $arg;
}
} else {
$_ARG['input'][] = $arg;
}
}
return $_ARG;
}
?>
Sample:
eromero@ditto ~/workspace/snipplets $ foxogg2mp3.php asdf asdf --help --dest=/var/ -asd -h
Array
(
[input] => Array
(
[0] => /usr/local/bin/foxogg2mp3.php
[1] => asdf
[2] => asdf
)
[help] => 1
[dest] => /var/
[a] => 1
[s] => 1
[d] => 1
[h] => 1
)
22-Oct-2007 11:11
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
<?php
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);
// Display user response & exit
echoAT(12,10,"Pressed : $key\n");
?>
Hope this helps someone.
22-Oct-2007 04:01
I have not seen in this thread any code snippets that support the full *nix style argument parsing. Consider this:
<?php
print_r(getArgs($_SERVER['argv']));
function getArgs($args) {
$out = array();
$last_arg = null;
for($i = 1, $il = sizeof($args); $i < $il; $i++) {
if( (bool)preg_match("/^--(.+)/", $args[$i], $match) ) {
$parts = explode("=", $match[1]);
$key = preg_replace("/[^a-z0-9]+/", "", $parts[0]);
if(isset($parts[1])) {
$out[$key] = $parts[1];
}
else {
$out[$key] = true;
}
$last_arg = $key;
}
else if( (bool)preg_match("/^-([a-zA-Z0-9]+)/", $args[$i], $match) ) {
for( $j = 0, $jl = strlen($match[1]); $j < $jl; $j++ ) {
$key = $match[1]{$j};
$out[$key] = true;
}
$last_arg = $key;
}
else if($last_arg !== null) {
$out[$last_arg] = $args[$i];
}
}
return $out;
}
/*
php file.php --foo=bar -abc -AB 'hello world' --baz
produces:
Array
(
[foo] => bar
[a] => true
[b] => true
[c] => true
[A] => true
[B] => hello world
[baz] => true
)
*/
?>
27-Sep-2007 02:54
an another "another variant" :
<?php
function arguments($argv)
{
$_ARG = array();
foreach ($argv as $arg)
{
if (preg_match('#^-{1,2}([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
Array
(
[input] => Array
(
[0] => myscript.php
[1] => arg1
)
[arg2] => val2
[arg3] => arg3
[arg4] => true
[arg5] => true
[arg5] => false
)
16-Aug-2007 09:24
For those who was unable to clear the windows screen trying to run CLS command:
CLS is not an windows executable file! It is an option from command.com!
So, the rigth command is
system("command /C cls");
22-Jul-2007 08:04
Just another variant of previous script that group arguments doesn't starts with '-' or '--'
<?php
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
)
[user] => nobody
)
25-Jun-2007 08:02
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.
04-Jun-2007 02:16
Just a variant of previous script to accept arguments with '=' also
<?php
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
)
12-May-2007 11:55
While working with command line scripts it is tedious to handle the arguments in a numerated array.
The following code will:
If the argument is of the form –NAME=VALUE it will be represented in the array as an element with the key NAME and the value VALUE. I the argument is a flag of the form -NAME it will be represented as a boolean with the name NAME with a value of true in the associative array.
<?php
function arguments($argv) {
$_ARG = array();
foreach ($argv as $arg) {
if (ereg('--[a-zA-Z0-9]*=.*',$arg)) {
$str = split("=",$arg); $arg = '';
$key = ereg_replace("--",'',$str[0]);
for ( $i = 1; $i < count($str); $i++ ) {
$arg .= $str[$i];
}
$_ARG[$key] = $arg;
} elseif(ereg('-[a-zA-Z0-9]',$arg)) {
$arg = ereg_replace("-",'',$arg);
$_ARG[$arg] = 'true';
}
}
return $_ARG;
}
?>
Example:
<?php print_r(arguments($argv)); ?>
# php5 myscript.php --user=nobody --password=secret -p
Array
(
[user] => nobody
[password] => secret
[p] => true
)
09-Apr-2007 12:27
I had a problem with PHP 5.2.0 (cli) (winXP) that no output was printed when I tried to run any file. Using the -n switch solved the problem.
Apparently the interpreter can't always find php.ini, even though both exist in the same folder and the PATH variable is set correctly. No error messages were printed either.
23-Mar-2007 08:48
i use emacs in c-mode for editing. in 4.3, starting a cli script like so:
#!/usr/bin/php -q /* -*- c -*- */
<?php
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:
#!/usr/bin/php -- /* -*- c -*- */
<?php
don't go back to your 4.3 system and replace '-q' with '--'; it seems to cause php to hang waiting on STDIN...
09-Mar-2007 04:14
To display colored text when it is actually supported :
<?php
echo "\033[31m".$myvar; // red foreground
echo "\033[41m".$myvar; // red background
?>
To reset these settings :
<?php
echo "\033[0m";
?>
More fun :
<?php
echo "\033[5;30m;\033[48mWARNING !"; // black blinking text over red background
?>
More info here : http://www.tldp.org/HOWTO/Bash-Prompt-HOWTO/x329.html
26-Nov-2006 05:46
Hi,
This function clears the screen, like "clear screen"
<?php
function clearscreen($out = TRUE) {
$clearscreen = chr(27)."[H".chr(27)."[2J";
if ($out) print $clearscreen;
else return $clearscreen;
}
?>
14-Nov-2006 09:57
An addition to my previous post (you can replace it)
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.
\Alon
It seems like 'max_execution_time' doesn't work on CLI.
<?php
php -d max_execution_time=20
-r '$foo = ini_get("max_execution_time"); var_dump($foo);'
?>
will print string(2) "20", but if you'l run infinity while: while(true) for example, it wouldn't stop after 20 seconds.
Testes on Linux Gentoo, PHP 5.1.6.
16-Sep-2006 12:59
On windows, you can simulate a cls by echoing out just \r. This will keep the cursor on the same line and overwrite what was on the line.
for example:
<?php
echo "Starting Iteration" . "\n\r";
for ($i=0;$i<10000;$i++) {
echo "\r" . $i;
}
echo "Ending Iteration" . "\n\r";
?>
21-Feb-2006 07: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
25-Sep-2005 09: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'));"
19-Sep-2005 09:27
I needed this, you proly wont tho.
puts the exicution args into $_GET
<?php
if ($argv) {
foreach ($argv as $k=>$v)
{
if ($k==0) continue;
$it = explode("=",$argv[$i]);
if (isset($it[1])) $_GET[$it[0]] = $it[1];
}
}
?>
16-Sep-2005 06: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.
14-Jul-2005 02: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.
24-Jun-2005 05: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:
<?php
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
30-May-2005 04: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!
26-May-2005 10: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
03-May-2005 05:29
#!/usr/bin/php -q
<?php
/**********************************************
* Simple argv[] parser for CLI scripts
* Diego Mendes Rodrigues - S�o 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]$
25-Apr-2005 10: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.
28-Mar-2005 11: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.
07-Mar-2005 05: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.
25-Feb-2005 05: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!
22-Feb-2005 08: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 !
09-Jan-2005 10: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
)
22-Dec-2004 06: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.
06-Feb-2004 03: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.
03-Feb-2004 04: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!
06-Aug-2003 06: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)
19-Jul-2003 01:18
You can use this function to ask user to enter something.
<?php
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.";
?>
17-Jun-2003 01: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
05-Jun-2003 12: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
18-Apr-2003 05: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.
20-Feb-2003 10:44
Here goes a very simple clrscr function for newbies...
function clrscr() { system("clear"); }
14-Feb-2003 02: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
07-Feb-2003 05: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.
22-Jan-2003 06: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!
22-Oct-2002 12: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.
21-Oct-2002 06: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);
?>
12-Oct-2002 05: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.
06-Sep-2002 02: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.
15-Aug-2002 08: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()...
04-Aug-2002 06: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.
14-Jun-2002 12: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);
?>
25-Feb-2002 11:02
18-Feb-2002 08: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.
