添加到PHP脚本中的$ PATH环境变量 [英] Adding to the $PATH environment variable in a PHP script

查看:181
本文介绍了添加到PHP脚本中的$ PATH环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个PHP脚本,使用 wget 来下载一些图像。但是,使用 Homebrew 安装 wget ,因此用户无法使用运行PHP脚本。当我运行 exec('echo $ PATH')我没有得到 / usr / local / bin 目录其中包含 wget 。如何将 / usr / local / bin 添加到环境路径中,以便PHP脚本可以找到 wget

更新:我忘了提到我无法指定确切位置的原因是因为位置可能会有所不同,具体取决于该脚本是



解决方案:



这是我最后的结论:

  //帮助PHP找到wget,因为它可能在/ usr / local / bin 
putenv('PATH ='。getenv('PATH ')。PATH_SEPARATOR。'/ usr / local / bin');
if(exec('which wget')== null){
throw new Exception('无法找到wget,因此无法下载图像。
}

//现在我们知道wget可用,所以下载图像
exec('wget ...');


解决方案

按照优先顺序:


  1. 当您调用子进程时,您可以简单地指定完整路径 / usr / local / bin / wget 。这可能是最简单和最好的方法。

  2. 您可以使用 proc_open ,而不是 exec ,它允许您将环境变量作为

  3. 您可以使用 putenv 来更改当前环境(将由子进程继承)。


I have a PHP script that is using wget to download some images. However, wget was installed using Homebrew so it's not available to the user running the PHP script. When I run exec('echo $PATH') I don't get the /usr/local/bin directory that contains wget. How do I add /usr/local/bin to the environment path so the PHP script can find wget?

Update: I forgot to mention the reason I can't specify the exact location is because the location may be different depending on which machine this script is being run on.

Solution:

This is what I ended up with:

//help PHP find wget since it may be in /usr/local/bin
putenv('PATH=' . getenv('PATH') . PATH_SEPARATOR . '/usr/local/bin');
if (exec('which wget') == null) {
    throw new Exception('Could not find wget, so image could not be downloaded.');
}

//now we know wget is available, so download the image
exec('wget ...');

解决方案

In order of preference:

  1. You can simply specify the full path /usr/local/bin/wget when you are calling the subprocess. This is probably the simplest and best approach.
  2. You can use proc_open instead of exec, which allows you to pass environment variables as an argument.
  3. You can use putenv to change the current environment (which will be inherited by subprocesses).

这篇关于添加到PHP脚本中的$ PATH环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆