使用 exec Laravel PHP 运行 .sh 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44374495/
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
Run .sh file using exec Laravel PHP
提问by Saurav
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 文件,该文件将一个 excel 文件导入我的数据库。这两个文件都在公用文件夹内的同一目录中。出于某种原因, exec 命令没有被执行,也没有发生任何错误。
.sh file colde:
.sh 文件冷:
IFS=,
while read column1
do
echo "SQL COMMAND GOES HERE"
done < file.csv | mysql --user='myusername' --password='mypassword' -D databasename;
echo "finish"
In my php file i have tried following:
在我的 php 文件中,我尝试了以下操作:
$content = file_get_contents('folder_name/file_name.sh');
echo exec($content);
And:
和:
shell_exec('sh /folder_name/file_name.sh');
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.
注意:我可以直接从 gitbash 执行 sh 文件,但是我希望它使用 Laravel 控制器中的函数来完成。我正在使用 Windows 操作系统。
回答by Alessandro Minoccheri
you can use Process Component of Symfony that is already in Laravel http://symfony.com/doc/current/components/process.html
您可以使用 Laravel http://symfony.com/doc/current/components/process.html 中已有的 Symfony 的 Process Component
use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;
$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();
回答by Alexander Kim
All of these answers are outdated now, instead use (Symfony 4.2 or higher):
所有这些答案现在都已过时,请改用(Symfony 4.2 或更高版本):
$process = Process::fromShellCommandline('/deploy.sh');
Or
或者
$process = new Process(['/deploy.sh']);
回答by CloudSPRT
I know this is a little late but I can't add a comment (due to being a new member) but to fix the issue in Windows " 'sh' is not recognized as an internal or external command, operable program or batch file." I had to change the new process from:
我知道这有点晚了,但我无法添加评论(由于是新成员),但为了解决 Windows 中的问题,“'sh' 未被识别为内部或外部命令、可运行的程序或批处理文件。 ” 我不得不改变新的流程:
$process = new Process('sh /folder_name/file_name.sh');
to use the following syntax:
使用以下语法:
$process = new Process('/folder_name/file_name.sh');
The only problem with is that when uploading to a Linux server it will need to be changed to call sh.
唯一的问题是,当上传到 Linux 服务器时,需要将其更改为调用 sh。
Hope this helps anyone who hit this issue when following the accepted answer in Windows.
希望这可以帮助任何在遵循 Windows 中接受的答案时遇到此问题的人。