我需要从控制器执行 shell 命令,但不仅限于项目内的文件,例如。系统('rm /var/www/html/test.html')或系统('sudo unzip /var/www/html/test.zip');
我调用该函数但没有任何反应,知道如何从控制器执行外部 shell 命令,例如删除另一个目录中的一个文件吗?
system('rm /var/www/html/test.html');
//or
exec('rm /var/www/html/test.html')
如果您想从 PHP 应用程序运行命令,我建议使用 Symfony Process Component:
运行
composer require symfony/process
使用
use Symfony\Component\Process\Process;
将课程导入到您的文件中
执行命令:
$process = new Process(['rm', '/var/www/html/test.html']);
$process->run();
如果您使用 Laravel,您应该可以跳过第 1 步。
或者,(如果运行 php 的进程具有正确的权限)您可以简单地使用 PHP 的 unlink() 函数来删除文件:
unlink('/var/www/html/test.html');
我会使用框架已经提供的功能来做到这一点:
1)首先生成命令类:
php artisan make:command TestClean
这将在 App\Console\Commands 中生成一个命令类
然后在该命令类的handle方法中写入:
@unlink('/var/www/html/test.html');
为您的命令提供名称和描述并运行:
php artisan list
只是为了确认您的命令已列出。
2)在你的控制器中导入Artisanfacade。
use Artisan;
3) 在控制器中写入以下内容:
Artisan::call('test:clean');
更多使用请参考文档: https://laravel.com/docs/5.7/artisan#generate-commands
使用fromShellCommandline来使用直接shell命令:
use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;
$process = Process::fromShellCommandline('rm /var/www/html/test.html');
$process->run();
// executes after the command finishes
if (!$process->isSuccessful()) {
throw new ProcessFailedException($process);
}
echo $process->getOutput();