Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute external shell commands from laravel controller?

I need to execute shell commands from controller , but not only for files inside the project , ex. system('rm /var/www/html/test.html') or system('sudo unzip /var/www/html/test.zip');

I call the function but nothing happen , any idea how to execute external shell commands from controller like removing one file in another directory?

system('rm /var/www/html/test.html');
//or
exec('rm /var/www/html/test.html')
like image 652
AnonS Avatar asked Jan 19 '19 10:01

AnonS


People also ask

How do I run a shell script in PHP?

The shell_exec() function is an inbuilt function in PHP which is used to execute the commands via shell and return the complete output as a string. The shell_exec is an alias for the backtick operator, for those used to *nix.

What is Laravel command line interface?

Artisan is the name of the command-line interface included with Laravel. It provides a number of helpful commands for your use while developing your application. It is driven by the powerful Symfony Console component.


2 Answers

If you're wanting to run commands from your PHP application I would recommend using the Symfony Process Component:

  1. Run composer require symfony/process

  2. Import the class in to your file with use Symfony\Component\Process\Process;

  3. Execute your command:

    $process = new Process(['rm', '/var/www/html/test.html']);
    
    $process->run();
    

If you're using Laravel, you should be able to skip Step 1.


Alternatively, (if the process running php has the correct permissions) you could simply use PHP's unlink() function to delete the file:

unlink('/var/www/html/test.html');
 
like image 108
Rwd Avatar answered Sep 18 '22 05:09

Rwd


I would do this with what the framework already provide:

1) First generate a command class:

php artisan make:command TestClean

This will generate a command class in App\Console\Commands

Then inside the handle method of that command class write:

@unlink('/var/www/html/test.html');

Give your command a name and description and run:

php artisan list

Just to confirm your command is listed.

2) In your controller import Artisan facade.

use Artisan;

3) In your controller then write the following:

Artisan::call('test:clean');

Please refer to the docs for further uses: https://laravel.com/docs/5.7/artisan#generating-commands

like image 32
Eden Reich Avatar answered Sep 17 '22 05:09

Eden Reich