当shell调用时,PHP system()调用不起作用

问题描述 投票:1回答:1

我有一个由cron运行的shell文件:

* * * * * /bin/sh /var/www/test.sh > /dev/null 2>&1

该文件只包含以下行:

php -q /var/www/test.php

那个php文件包含这个:

<?php
$command = 'cairosvg -f pdf -o /var/www/test.pdf /var/www/test.svg';
system($command);
$command = 'mkdir /var/www/test_dir';
system($command);
file_put_contents('var/www/test_user.log', posix_getpwuid(posix_geteuid())['name']);
if (file_exists('/var/www/test.pdf')) {
    file_put_contents('/var/www/test.log', 'success');
} else {
    file_put_contents('/var/www/test.log', 'fail');
}

cairosvg是一个CLI库,可将SVG文件转换为PDF。如果我完成上述步骤,则会运行此PHP代码,但不会创建该文件。如果我通过URL调用PHP文件,则会创建该文件。

我看到的唯一区别是进程用户posix_getpwuid(posix_geteuid())['name']是由URL运行的www-dataroot运行时由shell运行。

当我在终端以root身份运行它时,命令cairosvg -f pdf -o /var/www/test.pdf /var/www/test.svg正常工作。

第二个命令mkdir /var/www/test_dir只是一个现实检查,以确保system()启用CLI或其他非常简单的东西。该命令适用于shell和URL。

这是一个关于更复杂系统问题的最小,完整和可验证的例子,因此“跳过shell步骤”或类似的答案对我来说不会有什么帮助。

我正在运行PHP 5.6,Ubuntu 14.04和Apache。

当我通过shell调用而不是通过URL调用时,为什么这个PHP代码会失败?

php linux shell
1个回答
0
投票

在评论中归功于Nico Haase,pomaxa和kvantour。

system()返回状态给出127.这表示用户(root)无法识别cairosvg命令。我将/usr/bin/cairosvg符号化为/usr/local/bin/cairosvg,这让一切正常。

shell中的root无法访问cairosvg local的原因是CRON下的explained here在受限制的环境中运行你的命令。

可用的环境变量可能非常有限。通常,您只会定义一些变量,例如$ LOGNAME,$ HOME和$ PATH。

© www.soinside.com 2019 - 2024. All rights reserved.