laravel 如何从laravel控制器执行外部shell命令?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/54266041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 18:15:29  来源:igfitidea点击:

How to execute external shell commands from laravel controller?

phplinuxlaravelshellcontroller

提问by AnonS

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');

我需要从控制器执行 shell 命令,但不仅限于项目内的文件,例如。system( 'rm /var/www/html/test.html') 或 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?

我调用了该函数但什么也没发生,知道如何从控制器执行外部 shell 命令,例如删除另一个目录中的一个文件吗?

system('rm /var/www/html/test.html');
//or
exec('rm /var/www/html/test.html')

回答by Rwd

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

如果您想从 PHP 应用程序运行命令,我建议使用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();
    
  1. composer require symfony/process
  2. 将类导入到您的文件中 use Symfony\Component\Process\Process;
  3. 执行你的命令:

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


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

或者,(如果运行 php 的进程具有正确的权限)您可以简单地使用 PHP 的unlink()函数来删除文件:

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

回答by Eden Reich

I would do this with what the framework already provide:

我会用框架已经提供的东西来做到这一点:

1) First generate a command class:

1)首先生成一个命令类:

php artisan make:command TestClean

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

这将在 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.

2) 在您的控制器中导入 Artisan 外观。

use Artisan;

3) In your controller then write the following:

3)然后在你的控制器中写下以下内容:

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

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

更多使用请参考文档:https: //laravel.com/docs/5.7/artisan#generating-commands