Reputation: 1421
I'm running on Ubuntu server 14.04.
I have a PHP file that needs to read an environment variable and use it.
How can I do that?
Upvotes: 5
Views: 22277
Reputation: 3143
There is another way of doing it and its doing this on the apache side incase you want to migrate the change on to another server:
Basically it's having the following entry in /etc/environment file
export MY_PROJECT_PATH=/var/www/my-project
export MY_PROJECT_ENV=production
export [email protected]
export MY_TETS_ENV=my_test_env_value
You'll need to configure apache to read those environment variables.
This has already been answered on stack overflow: @ref: How to get system environment variables into PHP while running CLI & Apache2Handler?
Upvotes: 0
Reputation: 1421
If you run a PHP file (e.g. test.php) on Ubuntu server and you need to read and use an environment variable, you need to do the following:
Edit the .bashrc file (in case you run bash as a shell)
# Add the following:
export DB_NAME="My database name"
IMPORTANT: Do not forget the export word!
Save the file and exit.
click the following command:
source ~/.bashrc
check that the Environment variable is valid
echo $DB_NAME
It should print:
My database name
Edit your PHP file:
<?php
$db = getenv('DB_NAME'); // Gets the database name
echo "Database name: $db \r\n"
?>
Run the PHP file
php test.php
It should print
Database name: My Database name
Upvotes: 9