drzil26260 2017-12-18 14:50
浏览 364
已采纳

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

I have a shell file that I run by cron:

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

That file contains just this line:

php -q /var/www/test.php

That php file contains this:

<?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 is a CLI library that turns SVG files into PDFs. This PHP code runs if I go through the steps above, but the file isn't created. If I call the PHP file through URL, the file is created.

The only difference I see is that the process user posix_getpwuid(posix_geteuid())['name'] is www-data when ran by URL and root when ran by shell.

The command cairosvg -f pdf -o /var/www/test.pdf /var/www/test.svg works when I run it myself in terminal as root.

The second command, mkdir /var/www/test_dir is just a reality check to ensure that system() is enable for CLI or something else extremely simple. That command works by both shell and URL.

This is a Minimal, Complete, and Verifiable example of a problem on more complex system, so "skip the shell step" or similar answers aren't going to be very helpful for me.

I am running PHP 5.6, Ubuntu 14.04, and Apache.

Why is this PHP code failing when I call by shell rather than when I call it by URL?

  • 写回答

1条回答 默认 最新

  • dongqiao2077 2017-12-18 16:35
    关注

    Credit goes to Nico Haase, pomaxa and kvantour in the comments.

    system() return status gives 127. That indicates the user (root) didn't recognize the cairosvg command. I symlinked /usr/bin/cairosvg to /usr/local/bin/cairosvg and that got everything working.

    The reason root inside of shell didn't have access to cairosvg local is explained here under CRON runs your command in a restricted environment.

    What environment variables are available is likely to be very limited. Typically, you'll only get a few variables defined, such as $LOGNAME, $HOME, and $PATH.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算