如何从PHP中获取环境变量PHP / phpinfo()
我试图使用SendGrid的API,我需要使用以下命令访问我添加到我的根目录的环境变量。
I'm trying to use SendGrid's API for which I need to access an environment variable that I've added to my root directory using the following command.
echo "export SENDGRID_API_KEY='YOUR_API_KEY'" > sendgrid.env
echo "sendgrid.env" >> .gitignore
source ./sendgrid.env
这创建了一个我的根文件夹中的sendgrid.env
文件,将 sendgrid.env
添加到我的 .gitignore
文件,并将 SENDGRID_API_KEY
添加为环境变量。
This has created a sendgrid.env
file in my root folder, added sendgrid.env
to my .gitignore
file, and added SENDGRID_API_KEY
as an environment variable.
但是,PHP的 getenv 'SENDGRID_API_KEY')
键不返回任何东西,PHP的 phpinfo()
不反映 SENDGRID_API_KEY
作为一个环境变量。
However, PHP's getenv('SENDGRID_API_KEY')
key is not returning anything, and PHP's phpinfo()
does not reflect SENDGRID_API_KEY
as an environment variable.
这里是 API安装说明。
这意味着您应该使用另一个包来阅读 .env
文件。 示例在他们的官方网站使用 Dotenv
类将文件的内容加载到环境中:
It is implied that you should use another package for reading the .env
files. There is a sample on their official site that uses a Dotenv
class to load contents of the files into environment:
<?php
require 'vendor/autoload.php';
Dotenv::load(__DIR__);
$sendgrid_apikey = getenv('YOUR_SENDGRID_APIKEY');
尽管如此,他们甚至没有解释课程来自哪里。显然,这意味着您应该安装 vlucas / phpdotenv
包。请注意,在这个软件包的当前版本中, load
方法是非静态的(实际上在早期版本中是静态的):
Still, they don't even explain where the class comes from. Apparently, they mean that you should install vlucas/phpdotenv
package. Note, that in the current version of this package, the load
method is non-static (it actually was static in early versions):
$dotenv = new Dotenv\Dotenv(__DIR__);
$dotenv->load();