Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ubuntu: How PHP can read Environment Variable

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?

like image 296
raven99 Avatar asked Mar 16 '15 14:03

raven99


1 Answers

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:

  1. 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!

  2. Save the file and exit.

  3. click the following command:

    source ~/.bashrc
    
  4. check that the Environment variable is valid

    echo $DB_NAME
    

    It should print:

    My database name
    
  5. Edit your PHP file:

    <?php
      $db = getenv('DB_NAME'); // Gets the database name
      echo "Database name: $db  \r\n"
    ?>    
    
  6. Run the PHP file

    php test.php
    

    It should print

    Database name: My Database name
    
like image 126
raven99 Avatar answered Sep 24 '22 05:09

raven99