Home > Article > Backend Development > How to determine whether the exec function is executed successfully in PHP? _php instance
Foreword
To build a code release system, you need to use PHP's exec function to execute commands under Linux and git, svn commands. How to judge whether PHP's exec function is executed successfully?
Solution
Write a PHP file to do the experiment:
exec functionThe first parameter is the executed command, the second parameter is the execution result, and the third parameter is the execution status.
<?php exec('ls', $log, $status); print_r($log); print_r($status); echo PHP_EOL;
Execute this php file:
Here$log,$statusThe output results are as shown in the figure.
But $status is 0, which gives the impression that the execution failed. In fact, it is not. This is a successful exec execution.
Change this php file and give an incorrect command to the first parameter of exec.
For example: exec(‘lsaa’,$log,$status).
Execute again, the running result is as shown in the figure:
Here$status is indeed valuable.
Then it is proved that when $status is 0, it means that the exec execution is successful. There is no clear explanation in the official PHP manual here.
The final method of executing the command is as follows:
PHP exec execute command 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; }
Removed logging and other judgments.
Attention here:
$this->status = !$status;
Take the opposite value when returning the status!
Summary
The above are the details and example codes for judging whether the exec function is executed successfully in PHP, which will help you to have a deep understanding of PHP development. I hope that what this article describes will be helpful to everyone's learning of PHP development.