skip to Main Content

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


  1. Chosen as BEST ANSWER

    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 = DotenvDotenv::createImmutable(dirname(__DIR__));
        $dotenv->load();
    }
    

  2. 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 arguments should be space delimited. 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:

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search