Read environment varibles which is set using export command

In ubuntu, I am setting environment variables for database username and password as shown below.

export USERNAME=username
export PASSWORD=password

In Yii I want to write PHP code to read those values for creating the database connection. I used getenv() which is provided by PHP.

$username = getenv(USERNAME);
$password = getenv(PASSWORD);

This does not work. $username and $password are empty.

Note: If I do the same thing in a separate PHP file and run it using php run command, it works.

How can I solve this issue?

First of all yor mistake quotes:

$username = getenv('USERNAME');
$password = getenv('PASSWORD');

And problem is in your system user. You export variable in current logged user, run in console from this user, and var is set. But PHP on server used other user, www-data

Type in your script:

echo "\n" . $_SERVER['USER'] . "\n" . getenv('USERNAME') . "\n";
echo exit;

And run in console and in browser

@DeryabinSergey, Thanks a lot you for your answer. According to that, Should I set the variable in etc/apache2/envvars?

I think yes, try it.
Check that there will be no problems when running the script from cron or console.

sudo -u www-data yii command/action


sudo -u www-data php youScript.php

What profit of this action?

My actual use case is that, I want to set database usename and password as environment variables(export USENAME=‘root’) and those variables need to be read. I am going to do this to increase the security level of the project.

I’m not sure if this will add security.

Firstly, the connection to the base should only be from a local machine or an internal subnet. And if an attacker penetrated the server or infrastructure, it makes no difference where to look at the password from the database