It sounds like you’re looking to set up an environment variables file (often called a .env file, pronounced “dot-env”) to keep your sensitive credentials out of your public code. This is a standard best practice for security.
Here is how you set this up and, more importantly, how you make sure GitHub doesn’t see it.
1. Create the .env file
In the root directory of your project, create a new file named exactly .env. Inside, add your keys using a KEY=VALUE format. Do not use spaces around the equals sign.
API_KEY=your_secret_key_here
DATABASE_PASSWORD=your_password_here
2. Protect it with .gitignore
This is the most critical step. If you don’t do this, the .env file will be uploaded to GitHub. Create a file named .gitignore in your root directory and add the following line:
.env
> Note: If you have already pushed the .env file to GitHub, adding it to .gitignore now won’t delete the history. You will need to rotate your API keys immediately because they are technically compromised.
>
3. Access the variables in your code
Since you mentioned working with PHP, you can access these variables using a library like phpdotenv.
Installation
If you use Composer, run:
composer require vlucas/phpdotenv
Usage in PHP
At the top of your main PHP file, load the variables:
require ‘vendor/autoload.php’;
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();
// Access your key
$apiKey = $_ENV[‘API_KEY’];
4. Handling GitHub Actions or Hosting
Because the .env file is “ignored” and not on GitHub, your live website or GitHub Actions won’t have access to it.
* For GitHub Actions: Go to Settings > Secrets and variables > Actions in your repository to add “Repository Secrets.”
* For Web Hosting: Most hosts have a “Configuration” or “Environment Variables” section in their control panel where you manually input these pairs.
Suggested Article Titles
Securing PHP Applications with Environment Variables
Best Practices for Managing API Keys in Web Development
Understanding .gitignore for Beginners
Discover more from NathanLegakis.com
Subscribe to get the latest posts sent to your email.
Leave a Reply