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.
CodePudding user response:
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.
if(file_exists(dirname(__DIR__) . '/vendor/autoload.php')) {
require_once dirname(__DIR__) . '/vendor/autoload.php';
$dotenv = Dotenv\Dotenv::createImmutable(dirname(__DIR__));
$dotenv->load();
}
CodePudding user response:
I tried using SetEnv on the bottom of the httpd.conf file.
SetEnv API_KEY=MY_API_KEY
This method should have worked, except you have used the wrong syntax. There should be no =
between the key/value pairs. The above would have set an environment variable called API_KEY=MY_API_KEY
(instead of API_KEY
) and assigned an empty string!
It should simply be:
SetEnv API_KEY MY_API_KEY
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: