9
votes

I'm hosting my PHP project on AWS EC2 servers, using Elastic Beanstalk. I've set up my ENV Vars using php dotenv, which seem to be getting my vars just fine from my root .env file:

DbConnect.php:

require '../vendor/autoload.php';
$dotenv = new Dotenv($_SERVER['DOCUMENT_ROOT']);
$dotenv->load();

$DB_HOST = getenv('DB_HOST');
$DB_USERNAME = getenv('DB_USERNAME');
$DB_PASSWORD = getenv('DB_PASSWORD');
$DB_DATABASE = getenv('DB_DATABASE');

$mysqli = new mysqli($DB_HOST, $DB_USERNAME, $DB_PASSWORD, $DB_DATABASE);

So, in AWS Management Console, I set up the same named ENV vars within software configuration, git pushed, and re eb-deployed. I'm getting a 500 error because the EC2 ENV vars don't seem to be picking up.

enter image description here

Is there something else I need to do?


Update:

eb printenv displayed the correct env var values.

1
Didn't know who down vote it without any comments. The question looks OK for me with detail. If you downvoted, you'd better to give some reasonsBMW
You can always use eb printenv to make sure the env vars are what you expect them to be.Nick Humrich
Have you tried using the $_SERVER['DB_HOST'] syntax for all the envvars instead of getenv?Nick Humrich
@NickHumrich yes Nick, eb printenv printed the correct valuesGrowler
I would recommend trying $_ENV['DB_HOST'] as well. Though, they should all work the same. You could also validate the envvars are correctly making it to the php container by looking at phpinfo result.Nick Humrich

1 Answers

6
votes

Quote from https://github.com/vlucas/phpdotenv

phpdotenv is made for development environments, and generally should not be used in production. In production, the actual environment variables should be set so that there is no overhead of loading the .env file on each request. This can be achieved via an automated deployment process with tools like Vagrant, chef, or Puppet, or can be set manually with cloud hosts like Pagodabox and Heroku.

You will have php fatal error if you do not have .env file

Fatal error: Uncaught exception 'Dotenv\Exception\InvalidPathException' with message 'Unable to read the environment file at /home/vagrant/Code/project/.env.' in /home/vagrant/Code/project/vendor/vlucas/phpdotenv/src/Loader.php on line 75

If you would like Below is the sample code that you can set Environment Variable to check, it only load the Dotenv class if it is on local / testing environment

if(getenv('APP_ENV') === 'local' || getenv('APP_ENV') === 'testing')
{
    $dotenv = new Dotenv\Dotenv(__DIR__);
    $dotenv->load();
}

Or another method is check the .env file exist or not

$filePath = rtrim(__DIR__, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR . '.env';
if(is_file($filePath) && is_readable($filePath))
{
    $dotenv = new Dotenv\Dotenv(__DIR__);
    $dotenv->load();
}