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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With