Context
I’m developing a website in PHP and learned that I should keep certain information in an environment variable instead of hard-coding it into PHP variables. I learned that, on my local server, I needed the phpdotenv package to grab the contents of the .env file. After a while, I managed to properly set that up and got the .env file working on my local server.
The Problem
However, I’m having issues setting up the environment variables in my live server. I’m currently using Bluehost as my web host. I read that, when you’re in the live server, you don’t upload the .env file to the web root. Instead, you code the variables into either the session-wide environment variable files (~/.bash_profile, for example) or the system-wide environment variables (/etc/environment). First of all, is this true? Or is it okay to upload the .env file, along with the files for phpdotenv (if they’re outside of the web root directory), so that I can just use the code I already have? If so, why is this better than just hard-coding the values into PHP or using PHP constants or something like that?
Regardless, I used SSH to edit the contents of several files on the web host: the .bashrc file and .bash_profile file as well as the /etc/environment file. I added the correct key/value pairs (DB_NAME=databasename, for example), and it seems that it worked as I am able to see those variable values when I use the “env” command on the terminal. They even persist after unsetting them and then restarting the server. Also, I did put the variables into each of these three files, so let me know if that’s an issue.
The issue is that I am unable to access these variables in PHP. I’ve tried using getenv()
, $_ENV
, and $_SERVER
to no avail. Each of these functions lists a lot of content, but none of the variables I defined. Any idea how I can get the PHP to access these environment variables?
Things I’ve Tried
- I’ve already edited the php.ini file. I changed
variables_order = "GPCS"
tovariables_order = "EGPCS"
, enabling $_ENV super globals. I also editedallow_url_fopen
to “On”. - I’ve already tried restarting the server several times, but it doesn’t change the output of the PHP code.
- I’ve contacted Bluehost to ask if it’s an issue they can resolve, but they said they can’t. They gave me the fixes I’ve already tried.
Code
I tried thinking about what code would be necessary. Let me know if you need to see anything else. Here is the code I added to .bash_profile
:
export DB_SERVERNAME=servername
export DB_USERNAME=username
export DB_PASSWORD=password
export DB_NAME=databasename
Here is the code of my test.php file, which is located in the root of one of my folders for my website:
print_r($_ENV);
Let me know if you have any questions or need any other information.