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

Talk about how to execute Shell commands in Laravel?

藏色散人
Release: 2021-11-26 14:56:28
forward
3363 people have browsed it

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;
    }
}
Copy after login
  • 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!

Related labels:
source:learnku.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template