LoginSignup
0
3

More than 5 years have passed since last update.

phpでunixコマンドを実行する際に使うラッパー関数を作成した

Posted at

phpでunixコマンドを実行する事が多かったので、簡単な関数を作ってみました。
終了ステータスあり版となし版を作ってみました。

exec()(終了ステータスあり)

exec.php
function exec_cm($command){
  $command .= ' 2>&1'; //error内容出力
  exec($command, $output, $re);
  return [
    'output' => implode("\n", $output),
    'is_error' => ($re == 0) ? false : true
  ];
}

$command = 'cp test.txt test2.txt';

$re = exec_cm($command);
if($re['is_error']){ //エラーの場合のみ内容を出力
  echo $re['output'];
}

これで実行した場合、test2.txtが作成されます。
また、ファイルがなかったりしたら
cp: cannot stat ‘atest.txt’: No such file or directory%
って感じで出力されます。

exex()の場合終了ステータスは取れますが、出力結果が配列で返って来るため加工が必要です。

passthru()(終了ステータスなし)

exec.php
function exec_cm($command){
  $command .= ' 2>&1'; //error内容出力
  ob_start();
  passthru($command);
  $output = ob_get_clean();
  return $output;
}

$command = 'cp test.txt test2.txt';

$re = exec_cm($command);
echo $re;

これで実行した場合もexec()の時と同じ結果になります。
ただ、こちらは終了ステータスを見ることはできません。
標準出力と標準エラー出力をそのまま変数に突っ込みたい時などに使えそうです。

passthru()の場合終了ステータスは取れないですが、出力結果が未整形で返って来るためそのまま使えます。

まとめ

exec()
  終了ステータス取れる。
  出力は配列で返ってくるので加工しないといけない。

passthru()
  終了ステータス取れない。
  出力は未整形で返ってくるのでそのまま使える。
  ※実際は主に画像のバイナリを出力したりする時に使うみたいです。

phpの中で複数のunixコマンドを実行する必要がある時などは使えそうです。

0
3
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
0
3