从PHP一个简单的Linux脚本返回"Hello World"



好吧,很高兴接受投票以达到我的问题的最底层。我对Linux是全新的,但已经在Linux Cloud Server上托管了我的基于PHP的网站,并且需要运行FFMPEG脚本以转换视频。在Windows下,我有完整的应用程序工作,但是在Linux下,我似乎无法获得一个基本的脚本,并且想知道是否有人可以将我指向正确的方向。我已经阅读了有关此帖子的无数帖子,例如,从PHP运行bash命令,但这并不能帮助我到达底部。

这是我到目前为止所拥有的。

$old_path = getcwd();
chdir('videos/');
$new_path = getcwd();
echo('newpath '.$new_path); <-- this outputs 'old_path/videos'
$temp=  shell_exec('./testScript.sh');
echo ($temp) <-- produces nothing

测试脚本 testscript.sh 在视频目录中,只是

echo "hello world"

谢谢...

要做的第一件事是检查PHP实际上允许运行A shell脚本。

在命令提示符下运行以下内容

php -i | grep disable_functions

这应该用看起来像这样的行回复

disable_functions => no value => no value

但是,如果它返回包含shell_exec的字符串,则(可能包含其他内容)

disable_functions => shell_exec => shell_exec 

那么您将无法继续。此时的诀窍是尝试本地php.ini文件,看看是否可以关闭有问题的指令。

执行此操作将php.ini文件复制到您正在工作的目录。查找disable_functions => shell_exec => shell_exec行删除shell_exec。

然后在命令行上运行脚本

php -c php.ini myscript.php

但是,这可能完全受到云托管环境的限制

您也可以使用Apache Config和.htaccess进行此操作。

如果以上所有内容都可以,请检查testscript.sh的权限,并将其设置为可执行文件。这样做是

chmod +x testScript.sh

可悲的是,我的赌注是,受限制的云服务器环境将阻止您。

文件系统权限

在您的情况下,由于文件系统权限不足,脚本可能未执行。在Linux中,如果文件为当前用户或用户组设置了可执行文件,例如:

~/scripts/abc.php
./script.sh

否则,您应该将文件作为适当程序的参数传递,例如:

php ~/scripts/abc.php
/usr/bin/php ./script.php
bash ./script.sh

您可以使用lsstat命令检查文件系统权限:

$ stat --format='perm: %A | user: %U | group: %G' 1.sh
perm: -rwxr-xr-x | user: ruslan | group: users
$ ls -l 1.sh
-rwxr-xr-- 1 ruslan users 1261 Nov 26 11:47 1.sh

在上面的示例中,为用户ruslan和组users设置可执行位,但未设置为其他r--)。其他仅允许读取r)文件,但不能执行或写入文件。

要设置可执行位的位置使用chmod命令,例如:

# For the user
chmod u+x file.sh
# For the group
chmod g+x file.sh

更好地控制命令执行

shell_exec函数将写入标准输出描述符的内容返回。如果命令没有打印或失败,它将返回NULL。例如:

$out = shell_exec("ls -l inexistent-file");
var_dump($out); // NULL

因此,您对shell_exec的错误条件没有很好的控制。我建议改用prop_open

$cmd = 'ls -l 1.sh inexistent-file';
// Descriptors specification
$descriptors = [
  1 => ['pipe', 'w'], // standard output
  2 => ['pipe', 'w'], // standard error
];
// Open process for the command
$proc = proc_open($cmd, $descriptors, $pipes);
if (!is_resource($proc))
  die("failed to open process for $cmd");
if ($output = stream_get_contents($pipes[1])) {
  echo "output: $outputn";
}
fclose($pipes[1]);
if ($errors = stream_get_contents($pipes[2])) {
  fprintf(STDERR, "Errors: %sn", $errors);
}
fclose($pipes[2]);
// Close the process
if (($status = proc_close($proc)) != 0)
  fprintf(STDERR, "The command failed with status %dn", $status);

Shebang

考虑使用Shebang作为可执行脚本。示例:

#!/bin/bash -
#!/usr/bin/php

在shell脚本中必须写入解释器。

尝试以下:shell_exec('php ./testscript.sh');

编辑:使用正确的解释器(bash,sh ...)

更改PHP

最新更新