Guides › HTML / PHP sites › Security & hacks

Environment Variables and Secrets: Keep API Keys Out of Your Code

Secrets in code or public repos get stolen.

Reference guide. This guide is written from established practice and the official documentation of the tools involved. We have not yet tested every step on a live demo site. Back up your site before you change anything.
Security and hacking

API keys written into code or committed to a repository are easy to leak. Keep them in environment variables or a config file outside the public folder.

1Find hard-coded keys2Move them out3Read them in code4Protect the file5Rotate exposed keys6Restrict keys7Review accessFixed? Test the site. If not, get help.
The steps in order. Work down the list and stop when the problem is solved.

Step 1: Find hard-coded keys

Illustration for Step 1: Find hard-coded keys

Search your code for key, secret, token and password.

Step 2: Move them out

Illustration for Step 2: Move them out

Put values in a .env file or the host's environment variable settings.

Step 3: Read them in code

Illustration for Step 3: Read them in code

Use getenv('KEY') in PHP, process.env.KEY in Node or os.environ in Python.

Step 4: Protect the file

Illustration for Step 4: Protect the file

Keep .env outside the public web root and add it to .gitignore.

Step 5: Rotate exposed keys

Illustration for Step 5: Rotate exposed keys

If a key was ever public, revoke it and create a new one.

Step 6: Restrict keys

Illustration for Step 6: Restrict keys

Limit by domain, IP and permissions.

Step 7: Review access

Illustration for Step 7: Review access

Remove old keys and users.

Still stuck?

If these steps do not solve it, we fix it for you for a flat $99. Full refund if we do not solve it within 7 days.

Related guides

Did this solve it? If not, email hello@sitefixlab.org with the exact error text and we will look into it. Try the problem finder.

Last updated 2026-11-22.