【问题标题】:Why wget backticks shell command works in PHP CLI and not in a PHP script?为什么 wget backticks shell 命令适用于 PHP CLI 而不是 PHP 脚本?
【发布时间】:2014-12-27 16:01:59
【问题描述】:

只是为了好玩,我正在尝试从 php cli (/usr/bin/php -a) 下载 wget,它可以工作:

php > `wget -q -nd -O /Users/user/path/to/file.html http:\/\/host.com/some_file.html`;
php > // a HTML file is downloaded and its content is placed into /Users/user/path/to/file.html

但是,当我尝试从 PHP 脚本执行相同的操作时,它不起作用:

<?php 
 `wget -q -nd -O /Users/user/path/to/file.html http:\/\/host.com/some_file.html`;
 // After requesting the script from the browser and after the script is executed, the file doesn't exist on the specified path

我想说执行 apache 并因此执行 PHP 服务器端脚本的用户与从命令行执行 php 命令的用户相同(所以我想这应该不是权限问题)。

为什么如果我使用 .php 脚本并在脚本内调用 wget 文件不会保存?

感谢关注!

PS:请不要告诉我我可以使用 curl 来完成这样的任务,我知道我可以,我只是想知道如何在不使用 PHP 工具的情况下做类似的事情,仅此而已

【问题讨论】:

  • PHP日志有错误吗?
  • 可能wget不在apache用户的$PATH中?
  • @Barmar 不,php 错误日志中没有任何错误,我检查了 wget 应该在路径中,因为 apache 用户是我用来运行 php CLI 的同一用户命令
  • 守护进程可能不会运行 shell 启动脚本 .profile.bashrc,它们通常是设置环境变量的地方。所以即使是同一个userid,环境也不一样。
  • 也许您启用了safe_mode?这会禁用反引号。 shell_exec 有效吗?

标签: php shell wget shell-exec


【解决方案1】:

使用wget 的完整路径,因为守护程序不会运行.bash_profile

`/opt/local/bin/wget -q -nd -O /Users/user/path/to/file.html http://host.com/some_file.html`;

顺便说一句,没有必要在 shell 命令中转义 /

【讨论】:

  • 感谢您的建议!
【解决方案2】:

反引号操作符运行一个 shell 命令并返回 shell 命令的输出。

在这种情况下,简单地记录(或者如果必须,回显)结果可能会显示错误。例如:

$result = `wget -q -nd -O /Users/user/path/to/file.html http:\/\/host.com/some_file.html`;

trigger_error($result, E_USER_NOTICE);

【讨论】:

  • 没有帮助,$result 是一个空字符串。我发现了错误,请检查我的评论:)
  • 如果是路径问题 $result 应该是一个包含“sh: wget: command not found”的字符串
  • 是的,应该,但我不知道为什么我没有看到任何错误。可能是因为sh: wget: command not found 被写入标准错误?
猜你喜欢
  • 1970-01-01
  • 2011-03-28
  • 2019-02-03
  • 2015-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-05
相关资源
最近更新 更多