raven99
raven99

Reputation: 1421

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?

Upvotes: 5

Views: 22277

Answers (2)

unixmiah
unixmiah

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

raven99
raven99

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:

  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
    

Upvotes: 9

Related Questions