The tutorial column of Laravel below will introduce to you how to execute Shell commands in Laravel. I hope it will be helpful to you!
shell_exec()
and exec()
can both execute shell commands.
If your command crashes for unknown reasons, you won't know why - because shell_exec()
and exec()
No exception is thrown, they just fail silently.
Here's my solution:
use Symfony\Component\Process\Process; class ShellCommand { public static function execute($cmd): string { $process = Process::fromShellCommandline($cmd); $processOutput = ''; $captureOutput = function ($type, $line) use (&$processOutput) { $processOutput .= $line; }; $process->setTimeout(null) ->run($captureOutput); if ($process->getExitCode()) { $exception = new ShellCommandFailedException($cmd . " - " . $processOutput); report($exception); throw $exception; } return $processOutput; } }
Using this method, I can throw a custom exception, record the command and output, or log to the log to find problems.
Related recommendations: The latest five Laravel video tutorials
Original address: https://dev.to/kodeas/executing-shell -commands-in-laravel-1098
Translation address: https://learnku.com/laravel/t/63048
The above is the detailed content of Talk about how to execute Shell commands in Laravel?. For more information, please follow other related articles on the PHP Chinese website!