Govind Rai Govind Rai - 1 month ago 8
PHP Question

How to get Environment Variable from Shell in PHP/phpinfo()

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 and 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.

Answer

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();