使用 exec Laravel PHP 运行 .sh 文件

2022-01-23 00:00:00 shell command sh php laravel

我正在尝试运行一个 .sh 文件,该文件会将一个 excel 文件导入我的数据库.这两个文件都在公用文件夹内的同一目录中.由于某种原因,exec 命令没有被执行或没有任何错误发生.

I am trying to run a .sh file that will import a excel file to my database. Both files are in same directory inside the public folder. For some reason the exec command isn't being executed or neither any error occurs.

.sh 文件colde:

.sh file colde:

IFS=,
while read column1  
      do
        echo "SQL COMMAND GOES HERE"

done < file.csv | mysql --user='myusername' --password='mypassword' -D databasename;
echo "finish"

在我的 php 文件中,我尝试了以下操作:

In my php file i have tried following:

$content = file_get_contents('folder_name/file_name.sh');
echo exec($content);

还有:

shell_exec('sh /folder_name/file_name.sh');

注意:我可以直接从 gitbash 执行 sh 文件,但是我希望它使用 Laravel 控制器中的函数来完成.我正在使用 Windows 操作系统.

Note: I can directly execute the sh file from gitbash however I want it to be done using function in Laravel controller. I'm using windows OS.

推荐答案

你可以使用 Laravel 中已经存在的 Symfony 的 Process Component http://symfony.com/doc/current/components/process.html

you can use Process Component of Symfony that is already in Laravel http://symfony.com/doc/current/components/process.html

use SymfonyComponentProcessProcess;
use SymfonyComponentProcessExceptionProcessFailedException;

$process = new Process('sh /folder_name/file_name.sh');
$process->run();

// executes after the command finishes
if (!$process->isSuccessful()) {
    throw new ProcessFailedException($process);
}

echo $process->getOutput();

相关文章