在PHP中检索环境变量 [英] Retrieving an environment variable in php

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

问题描述

我正在Amazon Web Services上使用Linux EC2实例,在其中我通过执行将instance-id设置为环境变量

I am using a Linux EC2 instance on Amazon Web Services where I set up the instance-id as an environment variable by executing

export EC2_INSTANCE_ID=$(curl http://169.254.169.254/latest/meta-data/instance-id)

当我尝试使用$_ENV['EC2_INSTANCE_ID']getenv("EC2_INSTANCE_ID")从php中的变量检索数据时,出现错误:

When I try to retrieve the data from the variable in php using $_ENV['EC2_INSTANCE_ID'] or getenv("EC2_INSTANCE_ID") I get an error:

未定义索引:EC2_INSTANCE_ID

Undefined index: EC2_INSTANCE_ID

(此错误来自$ _ENV ['...'],getenv()根本不返回变量的值.)

(This error comes from $_ENV['...'], getenv() simply does not return the value of the variable.)

我已经通过设置variables_order = "EGPCS"在php.ini中设置了环境变量.

I already set up environment variables in the php.ini by setting variables_order = "EGPCS".

当我在命令行中运行printenv时,我会得到EC2_INSTANCE_ID=i-039......

When I run printenv in the command line I get EC2_INSTANCE_ID=i-039......

设置环境变量后,我使用service httpd restart重新启动了Apache.

I restarted apache by using service httpd restart after setting the environment variable.

那么php为什么不获取变量?

So why is php not fetching the variable?

推荐答案

如果执行 导出VARNAME =值 在外壳程序中,正如您在问题中所建议的那样,然后在Web服务器上运行的PHP程序将无法读取它. 例如,如果使用Apache,则需要在Apache配置中为该特定虚拟主机设置该变量.

If you execute export VARNAME=value in the shell, as you suggest in your question, then a PHP program running in a web server will not be able to read it. If you use Apache for example, then you will need to set that variable in the Apache configuration for that particular virtual host.. something like:

<VirtualHost ser.ver:80>
   SetEnv VARNAME value
</VirtualHost>

然后,该服务器上的PHP程序将能够按您期望的那样使用getenv()或$ _ENV读取该变量.

Then, a PHP program on that server will be able to read that variable with getenv() or $_ENV as you expect.

您描述的内容仅在您的PHP程序在计算机中作为客户端程序执行时才有效:

What you describe would only work if your PHP program is executed as client program in your computer:

$ export VARNAME=value
$ cat "<?php echo getenv('VARNAME'); ?>" > test.php
$ php test.php

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

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