做一个代码发布的系统,需要用到PHP的exec函数来执行Linux下的命令和git,svn命令,如何判断PHP的exec函数是否执行成功呢?
写个PHP文件来做实验:
exec函数第一个参数是执行的命令,第二个参数是执行的结果,第三个参数是执行的状态。
|
|
<?php
exec ( 'ls' , $log , $status ) ;
print_r ( $log ) ;
print_r ( $status ) ;
echo PHP_EOL ;
|
执行这个php文件:

这里$log,$status输出结果如图。
但是$status为0,给人的感觉是执行失败,其实不是,这是exec执行成功。
改一下这个php文件,给exec第一个参数一个错误的命令。
如:exec(‘lsaa’,$log,$status).
再次执行,运行结果如图:

这里$status确是有值的。
那么证明$status为0的时候表示exec执行是成功的。这里PHP官方手册上并没有明确说明。
最终这个执行命令的方法如下:
|
|
public function runLocalCommand ( $command ) {
$command = trim ( $command ) ;
$status = 1 ;
$log = '' ;
exec ( $command . ' 2>&1' , $log , $status ) ;
// 执行过的命令
$this -> command = $command ;
// 执行的状态
$this -> status = ! $status ;
return $this -> status ;
}
|
去除了日志记录和其他的判断。
注意这里:
|
|
$this -> status = ! $status ;
|
返回状态的时候取相反的值!
(原文网址:https://blog.tanteng.me/2016/07/php-exec-status/)
所有评论(0)