LoginSignup
1
0

More than 1 year has passed since last update.

PHPのexec関数でエラーメッセージを取得する

Posted at

PHPのexec関数では返り値や引数でコマンドの出力を取得できるが、エラーは取得できない。

// 存在しないディレクトリをlsする.
// $resultと$outputともに空
$result = exec('ls my-directory', $output);

なぜかというと、execコマンドで拾えるのは標準出力からの出力のみで、エラーの場合たいてい標準エラー出力からの出力になるため。エラーを拾うには最後に2>&1をつけて標準エラー出力の内容を標準出力にリダイレクトする。

$result = exec('ls my-directory 2>&1', $output);
// $result
"ls: cannot access 'my-directory': No such file or directory"

// $output
[
     "ls: cannot access 'my-directory': No such file or directory",
   ]

2は標準エラー出力、1は標準出力を指すファイルディスクリプタで、2>1だと1がファイル名だと解釈されるので&を付ける。

参考

https://stackoverflow.com/questions/345794/how-to-retrieve-php-exec-error-responses
https://stackoverflow.com/questions/818255/in-the-shell-what-does-21-mean

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