How to execute external shell commands from laravel controller?
Stefan Bogdanescu
Founder & Senior Architect · 2026-06-29
How to Execute External Shell Commands from Laravel Controller
When working with Laravel, it is often necessary to execute external shell commands directly in your controller. This may include file operations or running system-wide scripts outside the project's directory. Here's a comprehensive guide on how to achieve this.Using PHP's Native Function: system()
You can utilize the native PHP function 'system()' to execute external shell commands in your Laravel controller. Let's consider an example where you want to delete a file located outside your project directory. To do this, use the code below:php
public function removeFile() {
system('rm /var/www/html/test.html');
}Using PHP's exec()
Another option available in PHP is using 'exec()'. It works very much like 'system()', but it allows more control over command execution. For instance, you could use it with '&' to run a command in the background or pipe the output to another process:php
public function executeCommand() {
exec('rm /var/www/html/test.html &', $output);
}Using Artisan Commands for Ease and Security
If you wish to run shell commands in your application regularly or need added security measures, consider creating an Artisan command: 1. Create a new PHP artisan command using 'make:command'. For example: `php artisan make:command RemoveFileCommand` 2. Open the newly created command file (RemoveFileCommand.php) and add your desired logic to execute your shell commands, ensuring it's secure:php
public function handle() {
// Add your shell command execution code here
}