5

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?

raven99
  • 1,341
  • 4
  • 13
  • 28

2 Answers2

9

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
    
raven99
  • 1,341
  • 4
  • 13
  • 28
0

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 MY_PROJECT_MAIL=support@my-project.com

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?

Community
  • 1
  • 1
unixmiah
  • 3,081
  • 1
  • 12
  • 26