3

Environment Variables are used to set up the PHP application and the application runs smoothly. The issue that I'm facing is when I'm trying to reference the application's database connection file and run it from CLI.

Apache Set Up:

<VirtualHost *:80>
 DocumentRoot /var/www/html
 ServerName server.hostname.com
 SetEnv HOSTNAME 'hostname'
 SetEnv USERNAME 'username'
 SetEnv DB_PASSWORD 'password'
 SetEnv DB_NAME 'databaseName'
</VirtualHost>

The environment variables store all the connection-related data and the connection is referencing that.

Connection:

<?php

$username = $_SERVER['USERNAME'];
$password = $_SERVER['DB_PASSWORD'];
$hostname = $_SERVER['HOSTNAME'];
$database = $_SERVER['DB_NAME'];
error_reporting(0);
$mysqli = new mysqli($hostname, $username, $password, $database);

But, when I run it from CLI, it doesn't pick up the environment variables and it also doesn't let me run the cronjobs that are set up on the server because of the same reason.

sotirov
  • 4,455
  • This is because these variables are defined in apache virtualhost file and then passed to php-fpm (probably). This file is not being processed by the php cli because apache is not engaged in the cli stuff at all. You can put these variables into some "shared" config.php file and include it to every php cli script that needs them. – Michal Przybylowicz Aug 13 '19 at 16:47
  • @MichalPrzybylowicz I have a similar issue. Normally, on private servers, I'd set this vars on /etc/environment (which DOES get passed on to the CLI). However, I'm now working on a project that will run on a shared hosting environment (Dreamhost), where I cannot touch /etc/environment and using a shared config.php file is undesirable because I'd like to keep this variables outside of version control. Do you know of another way to do this? – Javier Larroulet Apr 22 '20 at 13:26

1 Answers1

2

If you are not on a shared hosting environment, you can put your vars on /etc/environment and they will be accessible via $_SERVER when running from the CLI.

Format would be:

HOSTNAME="hostname"
USERNAME="username"
DB_PASSWORD="password"
DB_NAME="databaseName"

No SetEnv, One per line.

This would allow to keep this potentially sensitive configuration values outside of your code (and therefore outside of version control) for added safety.