添加到PHP脚本中的$ PATH环境变量 [英] Adding to the $PATH environment variable in a PHP script
问题描述
我有一个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 ...');
按照优先顺序:
- 当您调用子进程时,您可以简单地指定完整路径
/ usr / local / bin / wget
。这可能是最简单和最好的方法。 - 您可以使用
proc_open
,而不是exec
,它允许您将环境变量作为 - 您可以使用
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:
- 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. - You can use
proc_open
instead ofexec
, which allows you to pass environment variables as an argument. - You can use
putenv
to change the current environment (which will be inherited by subprocesses).
这篇关于添加到PHP脚本中的$ PATH环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!