Before uploading my project to Github, I wanted to hide my API key using an environment variable.
I added this line of code inside .env file
API_KEY=MY_API_KEY
but when I call API_KEY in my PHP file,
$apiKey=getenv('API_KEY');
print_r($apiKey);
It shows nothing. And my site crashes because code didn’t get the API key.
I tried using SetEnv on the bottom of the httpd.conf
file.
SetEnv API_KEY=MY_API_KEY
but this still doesn’t work. print_r()
prints nothing. Just nothing…
What am I doing wrong?
Should the .env
file be located in the same location as the PHP file?
I am using windows and Xampp Apache is my web server.
2
Answers
As IMSoP mentioned in comment, I had to do something to force PHP to read my .env file and I solved this issue by installing phpdotenv. https://github.com/vlucas/phpdotenv This package makes available to read .env file.
This method should have worked, except you have used the wrong syntax. There should be no
=
between the key/value pairs. The arguments should be space delimited. The above would have set an environment variable calledAPI_KEY=MY_API_KEY
(instead ofAPI_KEY
) and assigned an empty string!It should simply be:
After changing
httpd.conf
you would need to restart Apache.Alternatively, add the directive to a
.htaccess
file in the document root. (Or relevant subdirectory.)Reference: