PHP 8.3.4 Released!

PHP ファイルの実行

CLI SAPI は、実行する PHP コードを 取得するために三種類の異なる手段をサポートしています。

  1. PHP に特定のファイルの実行を指示する。

    $ php my_script.php
    
    $ php -f my_script.php
    

    上記の方法は共に(-f スイッチの使用の如何に関らず) 指定したファイル my_script.php を実行します。 実行ファイルとしてあらゆるファイルを指定することができ、 PHP スクリプトは拡張子 .php で終わる必要がなく、任意の名前や拡張子を 使用することができます。

  2. 実行する PHP コードをコマンドラインで直接指定する。

    $ php -r 'print_r(get_defined_constants());'
    

    シェル変数の置換と引用符の使用については特に注意してください。

    注意:

    この例をよくみてください。開始/終了タグがありません! -r スイッチを使用した場合、これらのタグは不要と なります。これらのタグを使用するとパーサエラーを発生します。

  3. 実行する PHP コードを標準入力 (stdin)で指定する。

    これは強力な機能で、以下の(仮想的な)例に示すように、動的に PHP コードを生成し、実行バイナリに入力すること ができます。

    $ some_application | some_filter | php | sort -u > final_output.txt
    
これらのコードを実行する三種類の方法を組み合わせて使用することはできません。

他のシェルアプリケーションのように、PHP バイナリに 引数を指定することができるだけでなく、PHP スクリプトが この引数を取得することも可能です。スクリプトに指定できる 引数の数は PHP による制限を受けません (シェルは指定可能な文字数の最大値を設定しています。通常、この制限値を 越えることはできません)。スクリプトに指定した引数は、グローバル配列 $argv でアクセス可能です。 最初のインデックス (添字 0) には常に、 コマンドラインからコールしたスクリプト名が含まれています。 コマンドラインスイッチ -r を使ってインラインでコードを実行した場合は、 $argv[0] の値は "Standard input code" となることに注意しましょう。 PHP 7.2.0 より前のバージョンでは、 ダッシュ (-) でした。 STDIN の内容をパイプ経由で実行した場合も同じです。

登録される第 2 のグローバル変数は $argc で (スクリプトに指定された引数の数ではなく )、配列 $argv の要素数が含まれます。

スクリプトに指定する引数が文字 - で始まっていない 限り、特に留意すべきことはありません。スクリプトに指定する引数が文字 - で始まる場合、PHP 自体がこれを パースする必要があるとみなすため、問題を発生します。 これを防止するため、引数リストセパレータ -- を 使用してください。PHP にパースされる引数の後に このセパレータを置くと、その後の全ての引数はそのままパースされずに スクリプトに渡されます。

# これは、指定したコードを実行せずに PHP の使用法を示します
$ php -r 'var_dump($argv);' -h
Usage: php [options] [-f] <file> [args...]
[...]

# これは '-h' を引数として解釈し、PHP の使用法を表示しません
$ php -r 'var_dump($argv);' -- -h
array(2) {
  [0]=>
  string(1) "-"
  [1]=>
  string(2) "-h"
}

Unix システムでは、PHP をシェルスクリプトとして使用する他の手段があります。 最初の行が #!/usr/bin/php (必要に応じて、PHP CLI バイナリのパスを置き換えてください) で始まり、PHP の開始/終了タグの中に通常の PHP コードが続くスクリプトを書き、適当なファイル 実行属性を設定する(例: chmod +x test)ことが可能です。 この方法は、通常のシェル/Perl スクリプトと同様に実行することができます。

例1 シェルスクリプトとしての PHP スクリプトの実行

#!/usr/bin/php
<?php
var_dump
($argv);
?>

このファイルの名前が test で、カレントディレクトリに あるとすると、以下のように実行することができます。

$ chmod +x test
$ ./test -h -- foo
array(4) {
  [0]=>
  string(6) "./test"
  [1]=>
  string(2) "-h"
  [2]=>
  string(2) "--"
  [3]=>
  string(3) "foo"
}

見て分かるように、- で始まるスクリプトのパラメータを 指定する際に、特に注意する必要はありません。

PHP 実行バイナリは、Web サーバーから完全に独立して PHP スクリプトを 実行するために使用することができます。Unix システムを使用している場合、 実行可能とするためには PHP スクリプトの先頭に特別な一行を追加する必要が あります。これにより、システムがそのスクリプトを実行するプログラムを 知ることができます。 Windows 環境では、.php ファイルのダブルクリック オプションに php.exe を関連づけることができます。 または、PHP によりスクリプトを実行するバッチファイルを作成することも 可能です。Unix 上で動作させるためにスクリプトに追加された先頭行は、 Windows 環境での動作に悪影響を与えません。このため、この手法により、 クロスプラットフォーム環境で動作するプログラムを書くことができます。 コマンドライン PHP プログラムの書方の簡単な例を以下に示します。

例2 コマンドラインから実行されることを意図したスクリプト(script.php)

#!/usr/bin/php
<?php

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

これは、ひとつのオプションをとるコマンドラインの PHP スクリプトです。

使用法:
<?php echo $argv[0]; ?> <option>

<option> は出力したい単語です。
--help, -help, -h, あるいは -? を指定すると、
このヘルプが表示されます。

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

上のスクリプトでは、特殊な先頭行が用いられており、このファイルが PHP により実行されることを示しています。ここでは CLI 版を使用しているため、 HTTP ヘッダは出力されません。PHP で コマンドラインアプリケーションを使用する際には、2 つの変数 $argc および $argv を使用することが できます。 最初の変数は、引数の数に 1 (実行中のスクリプトの名前)を加えたものです。 2 番目の変数は、引数を保持する配列で、スクリプト名を有する 要素 0 ($argv[0]) から始まっています。

上のプログラムでは、引数が 1 より少ないかまたは多いかを調べています。 また、引数が --help, -help, -h または -? の場合、 ヘルプメッセージを出力し、動的にスクリプト名を出力します。 他の引数を受け取った場合、これを出力します。

上のスクリプトを Unix で実行する場合、実行可能とした後、 script.php echothis または script.php -h とする必要があります。 Windows では、この処理を行なう以下のようなバッチファイルを作成することができます。

例3 コマンドライン PHP スクリプトを実行するバッチファイル(script.bat)

@echo OFF
"C:\php\php.exe" script.php %*

上のプログラムが script.php という名前であるとし、 c:\php\php.exeCLI php.exe があるとすると、このバッチファイルは、追加オプション script.bat echothis または script.bat -h を指定して、スクリプトを実行します。

PHP のコマンドラインアプリケーションを拡張するために使用できるその他の関数については、 拡張モジュール Readline に関するドキュメントも参照ください。

Windows 環境で使用している場合、PHP の設定によって C:\php\php.exe や拡張子 .php の指定を不要にすることもできます。Micosoft Windows コマンドラインでの PHP を参照ください。

注意:

Windows では、実際に存在するユーザーアカウントの権限で PHP を実行することを推奨します。 "アカウント名とセキュリティID の間のマッピングは実行されませんでした。" というエラーのため、 ネットワークサービス経由で実行する特定の操作は失敗する場合があります

add a note

User Contributed Notes 7 notes

up
58
php at richardneill dot org
10 years ago
On Linux, the shebang (#!) line is parsed by the kernel into at most two parts.
For example:

1: #!/usr/bin/php
2: #!/usr/bin/env php
3: #!/usr/bin/php -n
4: #!/usr/bin/php -ddisplay_errors=E_ALL
5: #!/usr/bin/php -n -ddisplay_errors=E_ALL

1. is the standard way to start a script. (compare "#!/bin/bash".)

2. uses "env" to find where PHP is installed: it might be elsewhere in the $PATH, such as /usr/local/bin.

3. if you don't need to use env, you can pass ONE parameter here. For example, to ignore the system's PHP.ini, and go with the defaults, use "-n". (See "man php".)

4. or, you can set exactly one configuration variable. I recommend this one, because display_errors actually takes effect if it is set here. Otherwise, the only place you can enable it is system-wide in php.ini. If you try to use ini_set() in your script itself, it's too late: if your script has a parse error, it will silently die.

5. This will not (as of 2013) work on Linux. It acts as if the whole string, "-n -ddisplay_errors=E_ALL" were a single argument. But in BSD, the shebang line can take more than 2 arguments, and so it may work as intended.

Summary: use (2) for maximum portability, and (4) for maximum debugging.
up
6
email at alexander-bombis dot de
2 years ago
For Windows:

After the years I also have the fact that I have to use double quotation marks after php -r on Windows shell.

But in the Powershell you can use single or double quotation!
up
7
gabriel at figdice dot org
7 years ago
Regarding shebang:

In both Linux and Windows, when you execute a script in CLI with:

php script.php

then PHP will ignore the very first line of your script if it starts with:

#!

So, this line is not only absorbed by the kernel when the script file is executable, but it is also ignored by the PHP engine itself.

However, the engine will NOT ignore the first #! line of any included files withing your "outer" script.php.
Any "shebang" line in an included script, will result in simply outputting the line to STDOUT, just as any other text residing outside a <?php ... ?> block.
up
2
david at frankieandshadow dot com
7 years ago
A gotcha when using #!/usr/bin/php at the start of the file as noted above:

if you originally edited the file on Windows and then attempt to use it on Unix, it won't work because the #! line requires a Unix line ending. Bash gives you the following error message if it has DOS line endings:
"bash: /usr/local/bin/wpreplace.php: /usr/bin/php^M: bad interpreter: No such file or directory"

(In Emacs I used "CTRL-X ENTER f" then type "unix" and ENTER to convert)
up
0
spencer at aninternetpresence dot net
12 years ago
If you are running the CLI on Windows and use the "-r" option, be sure to enclose your PHP code in double (not single) quotes. Otherwise, your code will not run.
up
-8
petruzanautico at yah00 dot com dot ar
12 years ago
As you can't use -r and -f together, you can circumvent this by doing the following:
php -r '$foo = 678; include("your_script.php");'
up
-18
synnus at gmail dot com
5 years ago
in php.ini use auto_prepend_file="init.php"
first start script
To Top