PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

함수 레퍼런스> <기능
Last updated: Sun, 25 Nov 2007

view this page in

커맨드 라인에서 PHP 사용하기

버전 4.3.0부터 PHPCommand Line Interface를 의미하는 CLI라는 이름의 새로운 SAPI 타입 (Server Application Programming Interface)을 지원한다. SAPI는 이름에서 내포하듯이, 핵심 용도는 셀(또는 데스크탑) 응용프로그램을 PHP로 개발하는것에 맞춰져있다. 이 장에서 설명하는 CLI SAPISAPI사이에는 많은 차이가 있다. CLICGI는 많은 부분에 있어서 같은 동작을 하지만, 서로 다른 SAPI들이라는 것이다.

CLI SAPIPHP 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/phpsapi/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가 된다.

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에서는 헤더를 활성화시킬수 있는 스위치(switch)가 존재하지 않는다.

    CLI는 기본적으로 정숙모드(quiet mode)로 시작된다. 그러나 구버전의 CGI 스크립트와의 호환성을 위해 -q 스위치를 유지하고 있다.

    작업 디렉토리가 스크립트의 디렉토리로 변경되지 않는다 (-C스위치는 호환성을 유지됨)

    일반 텍스트 에러 메시지 (HTML 포맷이 아님)

  • 셀 환경에 맞지 않는 것들 때문에 CLI SAPI에 의해 오버로드되는 php.ini 지시자(directive)가 몇가지 존재한다.

    php.ini 지시자(directive) 오버로드
    지시자(directive) CLI SAPI 기본값 주석
    html_errors FALSE 셀에서 에러메시지를 읽을때 의미없는 HTML태그로 뒤범벅이 되면 에러메시지를 읽기가 매우 어려울수 있다. 따라서 이 지시자(directive)의 기본값은 FALSE다.
    implicit_flush TRUE print(), echo() 와 비슷한 함수들의 출력은 모두 즉시 출력으로 쓰기 되고 버퍼에 캐시되지 않는다. 표준 출력을 지연시키거나 조작하고 싶다면 output buffering을 사용할수도 있다.
    max_execution_time 0 (unlimited) 셀 환경에서 PHP를 무한 사용할 가능성때문에, maximum execution time은 unlimited로 설정된다. 웹 응용프로그램은 대부분 매우 빨리 실행이 끝나는 반면에 셀 응용프로그램은 더 많은 시간이 필요한 경우가 많다.
    register_argc_argv TRUE

    이 설정은 TRUE이기 때문에 CLI SAPI에서는 항상 argc (응용프로그램에 전달되는 인자의 수) 와 argv (응용프로그램에 전단되는 인자의 배열)을 사용할수 있을것이다.

    PHP 4.3.0에서부터, CLI SAPIPHP변수 $argc$argv가 등록되고 적절한 값으로 채워지게 된다. 이 변수의 생성은 CGIMODULE 버전과 같이 register_globalson되어 있어야 한다. 버전이나 register_globals의 설정에 관계없이, $_SERVER$HTTP_SERVER_VARS로 그 값에 접근할수 있다. Example: $_SERVER['argv']

    Note: 이 지시자(directive)는 설정 파일 php.ini나 사용자 설정으로부터 온 다른 값으로 초기화될수 없다. 모든 설정 파일이 해석되고 난 후에 기본값이 적용되기 때문에 이 것은 제한이 된다. 하지만, 각 값은 런타임동안에 변경될수 있다. (위 지시자(directive) 중 환경과 맞지 않는것 e.g. register_argc_argv).

  • 셀 환경에서의 작업을 편하게 하기 위해, 다음 상수가 정의되었다:

    CLI 전용 상수
    상수 설명
    STDIN stdin에 이미 열려진 스트림. 이 상수는 다음처럼 여는것을 간단하게 해준다.
    $stdin = fopen('php://stdin', 'r');
    STDOUT stdout에 이미 열려진 스트림. 이 상수는 다음처럼 여는것을 간단하게 해준다.
    $stdout = fopen('php://stdout', 'w');
    STDERR stderr에 이미 열려진 스트림. 이 상수는 다음처럼 여는것을 간단하게 해준다.
    $stderr = fopen('php://stderr', 'w');

    위에서 설명한대로 예를 들면 stderr에 대한 스트림을 직업 열필요가 없다. 스트림 자원 대신 단순하게 상수를 사용하면 된다.

    php -r 'fwrite(STDERR, "stderr\n");'
    이 스트림을 명시적으로 닫을 필요가 없다. 스크립트가 끝날때 PHP에 의해 자동적으로 닫히기 때문이다.

  • 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] [-- args...]
  -s               Display colour syntax highlighted source.
  -w               Display source with stripped comments and whitespace.
  -f <file>        Parse <file>.
  -v               Version number
  -c <path>|<file> Look for php.ini file in this directory
  -a               Run interactively
  -d foo[=bar]     Define INI entry foo with value 'bar'
  -e               Generate extended information for debugger/profiler
  -z <file>        Load Zend extension <file>.
  -l               Syntax check only (lint)
  -m               Show compiled in modules
  -i               PHP information
  -r <code>        Run PHP <code> without using script tags <?..?>
  -h               This help

  args...          Arguments passed to script. Use -- args when first argument 
                   starts with - or script is read from stdin

CLI SAPI는 실행하고자 하는 PHP코드를 취하는 3가지의 방법을 사용한다.

  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());'
    
    셀 변수 변환과 따옴표 사용에 있어서 특별한 주의가 필요하다.

    Note: 예제 코드를 주의깊에 읽으면, 시작과 끝 태그가 존재하지 않는다! -r 스위치는 그 태그들이 필요하지 않다. 그 태그들을 사용하면 해석 에러가 발생할것이다.

  3. 표준 입력(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) 스크립트는 보통의 셀이나 펄 스크립트처럼 실행될수 있다:

#!/usr/bin/php
<?php
    var_dump
($argv);
?>
이 파일이 현재 디렉토리에서 test라는 이름을 가졌다고 가정하면 다음과 같이 할수 있다.
$ chmod 755 test
$ ./test -h -- foo
array(4) {
  [0]=>
  string(6) "./test"
  [1]=>
  string(2) "-h"
  [2]=>
  string(2) "--"
  [3]=>
  string(3) "foo"
}
위와 같은 경우에 -로 시작하는 인자를 스크립트로 전달할때에도 주의할 필요가 없다.

커맨드 라인 옵션
옵션 설명
-s

색상으로 문법 강조된 소스를 보임.

이 옵션은 파일을 해석하여 HTML 강조된 버전을 만드는 내부적 메카니즘을 사용하여 표준출력에 그것을 쓰도록 한다. 주의할점은 이 옵션이 하는 일은 <code> [...] </code>블록의 HTML 태그를 생성하고, HTML 헤더는 생성하지 않는다는 것이다.

Note: 이 옵션은 -r 옵션과 함께 사용할수 없다.

-w

주석과 공백을 제거한 소스를 보임.

Note: 이 옵션은 -r 옵션과 함께 사용할수 없다.

-f

-f 옵션으로 주어진 파일명을 해석하고 실행함. 이 스위치는 선택적이고 생략가능하다. 파일명만 제공함으로써 실행이 가능하다.

-v

PHP, PHP SAPI, Zend 버전을 표준 출력에 출력함, e.g.

$ 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 가 위치한 디렉토리를 찾거나 , 사용자 정의의 INI 파일 디렉토리(php.ini라고 이름붙일 필요가 없다)를 설정할수 있슴. e.g.

$ php -c /custom/directory/ my_script.php

$ php -c /custom/directory/custom-file.ini my_script.php

-a

PHP를 대화식으로 실행함.

-d

이 옵션은 php.ini에서 허용된 설정 지시자(directive)에 대해서 사용자정의 값을 설정하도록 해줌. 문법은 다음과 같다:

-d configuration_directive[=value]

Examples (lines are wrapped for layout reasons):

# 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

디버거/분석표를 위한 확장 정보를 생성함.

-z

젠드 확장을 로드함. 파일명만 주어지면, PHP는 시스템의 현재 기본 라이브러리 경로에서 이 확장을 로드하려고 함(리눅스 시스템에서는 보통 /etc/ld.so.conf로 설정되어 있슴) 절대 결로 정보를 갖는 파일명을 전달하면 시스템 라이브러리 검색 경로를 사용하지 않을것이다. 디렉토리 정보를 갖는 상대경로의 파일명은 PHP에게 현재 디렉토리에서 상대경로의 확장만 로드하도록 한다.

-l

이 옵션은 주어진 PHP코드의 문법 검사만 수행하게 하는 편리한 방법을 제공함. 성공하면, No syntax errors detected in <filename>라는 메시지가 표준 출력으로 쓰여지고 셀의 리턴 코드는 0이다. 실패하면, 내부적인 해석기 에러와 함께 Errors parsing <filename>라는 메시지가 표준 출력으로 쓰여지고 셀의 리턴 코드는 255가 된다.

이 옵션은 치명적인 에러를 발견할수 없을것이다 (undefined functions 같은). -f 옵션을 사용하면 치명적인 에러도 함께 찾을수 있을것이다.

Note: 이 옵션은 -r 옵션과 함께 사용할수 없다.

-m

이 옵션을 사용하여, PHP는 내장(로드된)된 PHP 모듈과 Zend 모듈을 출력한다.

$ php -m
[PHP Modules]
xml
tokenizer
standard
session
posix
pcre
overload
mysql
mbstring
ctype

[Zend Modules]

-i 이 커맨드 라인 옵션은 phpinfo()를 호출하고, 결과값을 출력한다. PHP가 정확하게 동작하지 않으면, php -i를 사용하여 정보 테이블이나 그 테이블 이전에 어떤 에러 메시지가 출력되는지 보도록 지도될수 있다. 출력은 HTML내에 존재하고 따라서 꽤 많다는 것에 주의한다.
-r

이 옵션은 커맨드 라인에서 직접 PHP를 수행하도록 해줌. PHP의 시작과 끝 태그 (<?php?>)는 필요하지 않다. 만약 존재한다면 해석 에러가 발생할것이다.

Note: 이런 형태의 PHP를 사용할때 셀에 의해 수행되는 커맨드라인의 변수 치환과 충돌하지 않도록 주의가 필요하다.
Example showing a parser error

$ 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가 아닌 다른 셀을 사용 중이라면, 좀더 많은 다른 경험을 했을수 있다. 편하게 버그 보고를 열거나 phpdoc@lists.php.net에 메일을 보내도록 한다. 아직도 코드내로 셀변수를 취하려고 하거나 회피를 위한 역슬래쉬를 사용해서 어려움을 격기 쉽다. 분명히 경고했다.

Note: -rCLI SAPI에서만 사용가능하다. CGI SAPI 에서는 사용할수 없다.

-h 이 옵션으로 커맨드 라인의 실질적인 옵션 리스트에 관한 정보와 그들이 수행하는 작업에 대한 한줄의 설명을 볼수 있다.

PHP 실행 파일은 웹서버와 절대적으로 독립적인 PHP 스크립트를 실행하기 위해 사용될수 있다. 유닉스 시스템에 있다면, PHP 스크립트의 첫번째 줄에 특별한 것을 추가해야 하고, 실행가능하게 해서, 무슨 프로그램이 스크립트를 수행시킬지 시스템이 알수 있도록 한다. 윈도우 플랫폼에서는 .php파일의 더블 클릭 옵션을 갖는 php.exe와 연관시킬수 있거나, PHP를 통해 그 스크립트를 수행하도록 배치 파일을 만들수 있다. 유닉스에서 실행시키기위해 추가된 첫번째 줄은 윈도우에 아무런 해가 없을것이다. 그래서 이 방법을 사용하여 플랫폼 프로그램을 번갈아 작성할수 있다. 커맨드 라인 PHP 프로그램을 작성하는 단순한 에제 코드를 아래에서 볼수 있다.

Example#1 커맨드 라인에서 실행되도록 의도된 스크립트(script.php)

#!/usr/bin/php
<?php

if ($argc != || 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 echothisscript.php -h를 호출하면 된다. 윈도우에서는, 이 작업을 위해 배치 파일을 만들수 있다.

Example#2 커맨드 라인의 PHP 스크립트를 수행하기 위한 배치 파일(script.bat)

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

위 프로그램이 script.php이란 이름을 갖고, c:\php\cli\php.exe 안에 CLI php.exe를 갖는다면 이 배치 파일은 추가된 옵션과 함께 실행이 될것이다: script.bat echothisscript.bat -h.

PHP의 커맨드 라인 응용 프로그램의 기능을 확장하기 위한 좀더 많은 함수를 보기위해 Readline 확장에 대한 문서도 참고한다.



함수 레퍼런스> <기능
Last updated: Sun, 25 Nov 2007
 
add a note add a note User Contributed Notes
커맨드 라인에서 PHP 사용하기
thomas dot harding at laposte dot net
15-Jun-2008 07: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: */
?>
mortals at seznam dot cz
07-May-2008 05: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
safak ozpinar
29-Feb-2008 11: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);

?>
Anonymous
17-Feb-2008 02: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 ) );

?>
technorati at gmail dot com
12-Feb-2008 11: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

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;
}
earomero _{at}_ gmail.com
29-Oct-2007 08: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
)
james_s2010 at NOSPAM dot hotmail dot com
23-Oct-2007 06: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.
B Crawford
22-Oct-2007 11: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
)

*/
?>
losbrutos at free dot fr
27-Sep-2007 09: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
)
dino (at) asttra (dot) com (dot) br
17-Aug-2007 04: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");
lucas dot vasconcelos at gmail dot com
23-Jul-2007 03:04
Just another variant of previous script that group arguments doesn't starts with '-' or '--'

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

$ 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
)
bluej100@gmail
26-Jun-2007 03: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.
eric dot brison at anakeen dot com
04-Jun-2007 09: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
)
contact at nlindblad dot org
13-May-2007 06: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
)
Jouni
09-Apr-2007 07: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.
rob
24-Mar-2007 04: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 editingthe '-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...
djcassis at gmail
10-Mar-2007 12: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
jsa1971 at gmail dot com
06-Mar-2007 01:03
python coders might miss this construct when working in PHP:

if __name__=='__main__':
    # handle direct invocation from command line

it's a great way to embed little bits of test code (or a full-on cli for that matter),
while keeping the source file usable in other contexts.

Far as I can tell, this is the closest approximation available in PHP5:

if ('cli'===php_sapi_name() &&
    __FILE__===realpath(
        getcwd().DIRECTORY_SEPARATOR.$_SERVER['argv'][0]
        )) {
    // handle direct invocation from command line
}
jgraef at users dot sf dot net
27-Nov-2006 01: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;
  }
?>
goalain eat gmail dont com
14-Nov-2006 05: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
17-Sep-2006 03:05
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.
hobby6_at_hotmail.com
16-Sep-2006 07: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";
?>
goalain eat gmail dont com
21-Aug-2006 04:20
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 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
stromdotcom at hotmail dot com
22-Feb-2006 03: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 04: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
20-Sep-2005 04: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];
    }
}
?>
php at schabdach dot de
17-Sep-2005 01: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 05: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 09: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
25-Jun-2005 12: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 11: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
27-May-2005 05: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
03-May-2005 12: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