Home >PHP Framework >Laravel >Talk about how to execute Shell commands in Laravel?

Talk about how to execute Shell commands in Laravel?

藏色散人
藏色散人forward
2021-11-26 14:56:283409browse

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!

Talk about how to execute Shell commands in Laravel?

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;
    }
}
  • It uses Symfony's Process component. Related recommendations: The latest five Laravel video tutorials

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!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete