はじめに
PHPの exec()
関数は、シェルコマンドを実行し、その出力や終了ステータスを取得できる強力な関数です。
上級試験では「戻り値と $output
の違い」や「終了コードの取得方法」が問われることがあります。本記事では、具体例と図解で exec()
の挙動をわかりやすく整理します。
目次
exec() 関数の基本構文
exec(string $command, array &$output = null, int &$result_code = null): string|false
$command
:実行するシェルコマンド$output
:オプション。コマンド出力の各行を配列で格納$result_code
:オプション。コマンドの終了ステータスを格納- 戻り値:コマンド出力の最後の行のみ
ポイント:全体は $output
に格納され、最後の行だけが戻り値として返される
実行例
<?php
declare(strict_types=1);
error_reporting(-1);
$r = exec('vmstat 1 3', $output, $result_code);
var_dump($r, $result_code, $output);
出力例
string(82) " 0 0 0 6919132 32212 459736 0 0 0 0 141 134 0 0 100 0 0"
int(0)
array(5) {
[0]=> string(80) "procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu-----"
[1]=> string(80) " r b swpd free buff cache si so bi bo in cs us sy id wa st"
[2]=> string(82) " 0 0 0 6919192 32212 459580 0 0 36 1 50 75 0 0 100 0 0"
[3]=> string(82) " 0 0 0 6919132 32212 459736 0 0 0 0 513 677 0 0 100 0 0"
[4]=> string(82) " 0 0 0 6919132 32212 459736 0 0 0 0 141 134 0 0 100 0 0"
}
処理フロー図(理解用)
┌───────────────────────────────┐
│ PHPコード │
│ │
│ $r = exec('vmstat 1 3', │
│ $output, │
│ $result_code); │
└───────────────┬───────────────┘
│
▼
┌─────────────────────┐
│ シェルコマンド実行 │
│ 'vmstat 1 3' │
└─────────┬───────────┘
│
▼
┌──────────────────────────┐
│ コマンドの標準出力(全行) │
│ 0行目: "procs..." │
│ 1行目: " r b swpd ..." │
│ 2行目: " 0 0 0 ..." │
│ 3行目: " 0 0 0 ..." │
│ 4行目: " 0 0 0 ..." │
└─────────┬───────────────┘
│
┌────────┴─────────┐
│ │
▼ ▼
┌─────────────┐ ┌───────────────┐
│ $output配列 │ │ $r(戻り値) │
│ [0] = 0行目 │ │ 最後の行 │
│ [1] = 1行目 │ └───────────────┘
│ [2] = 2行目 │
│ [3] = 3行目 │
│ [4] = 4行目 │
└────────────┘
│
▼
┌───────────────┐
│ $result_code │
│ コマンド終了 │
│ 正常: 0 │
└───────────────┘
まとめ
$r
:最後の行だけを取得$output
:全行を配列で取得$result_code
:コマンド終了コード$output
配列は既存の値に追記されるため、必要ならunset($output)
でリセット- 上級試験では 戻り値と
$output
の違い、終了コードの取得がよく問われる