PHPで外部プログラムを実行しよう

nesys Add comments
タグ:
add to hatena hatena.comment (4) add to del.icio.us (1) add to livedoor.clip (1) add to Yahoo!Bookmark (0) Total: 6

phpで外部プログラムを実行する関数は主に3つある。system関数、exec関数、passthru関数の3つ。
他にもproc_open関数などと便利なものもあるが、今回は置いておこう。

それぞれの違いは返り値にあるわけだが、実際にコードを実行して違いを見てみよう。

system関数

PHP: system - Manual
http://jp.php.net/manual/ja/function.system.php

$dump = system("ls");
var_dump($dump);
test1.php
test2.php
test3.php
string(8) "test3.php"

system関数はコマンドの実行結果が文字列の形としてそのまま出力され、最後の行の文字列が返り値として返される。

exec関数

PHP: exec - Manual
http://jp.php.net/manual/ja/function.exec.php

$dump = exec("ls");
var_dump($dump);
string(8) "test3.php"

exec関数はsystem関数と違い、コマンドの実行結果が出力されず、返り値はsystem関数と同様に、実行結果の最後の行の文字列が返り値として返される。

passthru関数

PHP: passthru - Manual
http://jp.php.net/manual/ja/function.passthru.php

$dump = passthru("ls");
var_dump($dump);
test1.php
test2.php
test3.php
NULL

passthru関数はsystem関数と同様に実行結果が出力されるが、返り値はNULL。

結論

それぞれの利用は時と場合によるが、主にphpで外部プログラムを実行する場合に実行結果が出力されるのは邪魔となる場合が多いため、実行結果が出力されないexec関数を利用することが頻繁となるだろう。バックグラウンド処理を行いたい場合はここ参照。
稀に、phpからLinuxを操作する場合があるが、そういうときにsystem関数やpassthru関数が使われるのだろう。

関連エントリ

One Response to “PHPで外部プログラムを実行しよう”

  1. PHPでバックグラウンド処理をしよう - Cross System blog Says:

    [...] Older [...]

Leave a Reply

WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS ログイン