9
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

phpで外部コマンド実行結果をバイナリで受け取る

Last updated at Posted at 2014-04-21

phpで外部コマンド実行結果をバイナリで受け取る

外部コマンドの実行結果をexec()の第二引数で取得すると、
1行ごとの配列になってしまうし、バイナリセーフでないので。

ならstdoutをそのまま取得してしまえばいいじゃないか、という話。

php
    ob_start();
    passthru(<<<EOD
cat img.png
EOD
    );
    $output = ob_get_contents();
    ob_end_clean();

これで標準出力への出力を無加工でそのまま取得できる。

要点

  • passthru()

外部プログラムを実行し、未整形の出力を表示する

未整形の出力はいいけど、呼ぶとこの関数の中で出力までされてしまうので、

  • ob_start()
  • ob_end_clean()
  • ob_get_contents()

で標準出力をキャプチャすれば良い。

ちなみに

stdoutのキャプチャ自体は別にphpに限った話じゃないのでrubyとかpythonとかでも使える。
rubyの場合こんな感じ。

ruby
output = StringIO.open { |sio|
    begin
        $stdout = sio
        exec("cat img.png")
        sio.rewind
        sio.read
    ensure
        $stdout = STDOUT
    end
}

小ネタ

こんな事も出来る。

php
ob_start();
$some_args_pass_to_partial_script = array(1, 2, 3);
require("_partial.php");
$partial_script_contents = ob_get_contents();
ob_end_clean();
9
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?