Apparently, the documentation is not as clear as is should be.
Short Answer:
I had this same exact issue. Here's the answer I got, and I was actually able to implement code as displayed in the documentation. Basically you need to use a third party utility that parses .env
files and makes the data available to your PHP runtime.
From the utility's documentation, I learned environment variables are usually for development purposes only and that production code usually has real data (the secrets) hard coded. The whole .env
file (in this case sendgrid.env
and getenv('YOUR_API_KEY')
is so you don't need to necessarily share crucial data when sharing code such as on Github, hence the addition of the .env
file to .gitignore
. Read the original answer for a full back story and how to get getenv()
working!
Blows my mind why they wouldn't include such crucial data in the readme.md but its pretty messed up and a lot of people have been stuck. Maybe I'll submit a issue when I get time, but no promises.
Check out dotenv's .readme
for lots of clarity! :D
Long Answer:
If you're not sharing code (i.e. this is your personal project or your client doesn't care about sharing secrets), you don't need to set environment variables. Remove the getenv
lines from your code and hard code your key.
However, if you're collaborating then, ideally, you should figure out a way to not include sensitive information in the code you share. In Sendgrid's example, they use PHP
's getenv
function to retrieve sensitive data but don't really show how to store that data so that it is available in your PHP runtime. Apart from mini hints such as adding the sendgrid.env
file to .gitignore
(telling you that the sendgrid.env file won't be uploaded to a git repository), there is much information on how to make the contents of sendgrid.env (which is storing your api_key available to your PHP runtime. Hence, everytime you run your code, PHP wont actually be able to see your key.
However, a deeper search into their git repository and you see a more detailed example where they use a PHP utility dotenv whose entire purpose is to crawl .env files and allow PHP to parse information from those files.
Therefore, to get getenv('YOUR_API_KEY')
) to work you'll need to either use the dotenv
utility or, as I was told by SendGrid's community manager, "figure out on my own how to store environment variables securely and make them available to the PHP environment".