问题
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
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.
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.
Here are the API installation instructions.
回答1:
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');
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();
来源:https://stackoverflow.com/questions/40519792/how-to-get-environment-variable-from-shell-in-php-phpinfo