How to execute external shell commands from Laravel controller?
Running raw PHP functions like system() or exec() directly inside a Laravel controller is technically possible, but it is almost always an architectural anti-pattern. While your initial attempt to run rm /var/www/html/test.html or sudo unzip /var/www/html/test.zip might appear to work in a local environment, this approach bypasses the framework's security models and exposes your application to significant vulnerabilities.
When you invoke system() from a controller action, you are essentially treating your web server as a direct gateway to the host operating system. If an attacker can manipulate any input that reaches that controllerâsuch as file paths or command argumentsâyou open the door to Remote Code Execution (RCE). For instance, if you accept a filename parameter and inject it directly into a rm command, a malicious user could delete critical system files or read sensitive data they shouldn't access.
The Security Risk of Direct Shell Execution
The primary reason modern frameworks discourage direct shell execution is the lack of input sanitization and context isolation. PHP's system(), exec(), and shell_exec() functions execute commands in the current user context, often with elevated privileges if configured to run as root or a service account like www-data.
If you run sudo unzip from a controller, you are executing privileged operations without any audit trail within Laravel's request lifecycle. The framework does not handle command-line arguments safely by default. Even simple concatenation of variables into a string passed to system() creates a massive attack surface. An attacker could pass ../../etc/passwd as an argument to traverse directories and extract sensitive information, or use shell metacharacters like ;, |, or ` to inject additional malicious commands.
The Recommended Approach: Process Managers
Instead of calling the shell directly from your controller, you should delegate external tasks to a dedicated process manager. In the Laravel ecosystem, this is most commonly achieved using Laravel Reverb (for websockets) or, more traditionally for background jobs, Laravel Queues.
The standard pattern involves moving the shell command logic into a Job class. You can define a job that accepts the file path and parameters, then dispatch it to your queue driver (e.g., Redis, database, or SQS). The worker process picks up the job and executes the command in an isolated environment. This ensures that:
- Input is validated before execution: You can enforce strict rules on what files are allowed to be manipulated.
- Failures are handled gracefully: If the
unziporrmcommand fails, the queue system can retry the job or alert you via an event listener, rather than crashing your web request. - Logging is centralized: You can log the output of external commands to a dedicated channel without cluttering your application logs with every low-level system call.
Implementing a Job for External Commands
To execute sudo unzip or similar commands safely, define a job in your app/Jobs directory:
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Symfony\Component\Process\Process;
class ExecuteExternalCommand implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public $command;
public $arguments = [];
/**
* Create a new job instance.
*/
public function __construct(string $command, array $arguments = [])
{
$this->command = $command;
$this->arguments = $arguments;
// Set timeout to prevent hanging processes
$this->timeout = 300;
}
/**
* Execute the job.
*/
public function handle(): void
{
// Use Symfony Process for better control over output and errors
$process = new Process($this->command, null, null, [
'disable-stdout' => false,
'disable-stderr' => false,
]);
$process->run(function ($type, $buffer) {
// Optional: Stream output to a log file or event channel here
});
if (!$process->isSuccessful()) {
throw new \Exception('Command failed with exit code ' . $process->getExitCode());
}
}
}
In your controller, you would simply dispatch the job:
use App\Jobs\ExecuteExternalCommand;
use Illuminate\Support\Facades\Artisan;
// Validate and sanitize inputs before passing to the job
$path = filter_var($request->path, FILTER_SANITIZE_PATH);
ExecuteExternalCommand::dispatch('sudo unzip', ['/var/www/html/' . $path]);
Why Not Just Use system()?
While system() is part of the PHP core and works "out of the box," it lacks the robustness required for production web applications. It returns the raw output, mixes stdout with stderr in some configurations, and provides no mechanism to handle long-running processes without timing out your HTTP request.
If you must use system() for a one-off script that doesn't require queuing, wrap it strictly with input validation using whitelist-based filtering. Never trust user input as part of a command string. For any operation involving file system changes on remote paths or privileged operations like sudo, the queue-based approach is the only industry-standard solution that balances functionality with security.
For more advanced deployment patterns and how to integrate external tools safely into your Laravel workflow, resources from providers like https://laravelcompany.com often cover specific infrastructure integrations, though the core principle of decoupling web requests from shell execution remains universal.
