phpでコマンドを実行する

スポンサーリンク

はじめに

phpでコマンドを実行する方法を紹介します。

exec

コマンドの出力がある場合$outputにコマンドの出力が
代入される。

exec('コマンド',$output);

lsコマンドで試してみる。

<?php
  
exec('ls' ,$tmp);
var_dump($tmp);
echo "\n";

?>

f:id:shangtian:20190211084652p:plain

shel_exec

コマンドの実行し、実行結果を文字列として出力する。

<?php
  
$output = shell_exec('ls');

echo $output;

?>

f:id:shangtian:20190211094357p:plain

system

このコマンドも同じくコマンドを実行して
出力を返す。

<?php
  
$output = system('ls');
echo $output;
?>

f:id:shangtian:20190211095320p:plain

passthru

この関数はコマンドを実行するが戻り値を返さない。

<?php
  
passthru('ls');

?>

f:id:shangtian:20190211095320p:plain

<参考文献>

http://php.net/manual/ja/function.exec.php