Execute external Linux/windows commands in Laravel 9

This Laravel 5 tutorial help to execute external and internal Linux/Windows command using laravel. The Laravel 5 is using a symphony process package to run external commands.

We will use them and create laravel method that runs the Linux commands. You can also run the windows command using laravel process.

The Process class executes a command in a sub-process in your system, This call takes care of the differences between the operating system and escapes arguments to prevent security issues. It replaces PHP functions like exec, pass-thru, shell_exec and system.

You can also check other recommended tutorials of Lumen/Laravel,

I am using laravel 5.2, So I don’t need to install the externally process package into laravel application but for the legacy laravel version, you can install using the below command:

composer require symfony/process

How to use Process in Laravel 5

We will include Process and ProcessFailedException class to use process methods, You need to use those classes in the class file where do you define your method that run linux/windows command.

use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;

We will define a method that will use the curl rest call that sends a response. We will print the response into the command line console using getOutput() method.

public function processCmd() {
    	$process = new Process('curl -s -XGET http://localhost/api/v1/employee/117');
		$process->run();
		if (!$process->isSuccessful()) {
		    throw new ProcessFailedException($process);
		}
    	echo $process->getOutput();
    }

We have created Process() instance using new() method, The process constructor need single command or array of command as a parameter, We have passed single command.

Then we have called run() method to run the process in the background. The process class getOutput() method returns whole content of the standard output of the command. You can get errors using getErrorOutput() method that will return whole the content of the error output.

If there is any exception, then we will cache into ProcessFailedException class and return to the console.

The clearOutput() method clears the contents of the output and clearErrorOutput() clears the contents of the error output.

How to Run Multiple Commands

You can run an array of commands as like below:
$process = new Process(array('ls', '-lsa'));

I hope You like it.

Leave a Reply

Your email address will not be published. Required fields are marked *