Hiding DB Credentials WP
April 7, 2025 Β· AI Conversations
—
### β Recommended Approaches
#### 1. **Use Environment Variables (`.env`)**
– Install [vlucas/phpdotenv](https://github.com/vlucas/phpdotenv) (already included in frameworks like Bedrock).
– Create a `.env` file **outside** the web root and define DB credentials:
DB_NAME=your_db_name
DB_USER=your_db_user
DB_PASSWORD=your_secure_password
DB_HOST=localhost
– In your plugin, access them like this:
$db_name = getenv('DB_NAME');
$db_user = getenv('DB_USER');
$db_pass = getenv('DB_PASSWORD');
> π Note: Never commit `.env` to Git and restrict server access.
—
#### 2. **Define Constants in `wp-config.php`**
Instead of hardcoding DB info in your plugin:
– Store them in `wp-config.php`:
define('MYPLUGIN_DB_NAME', 'your_db_name');
define('MYPLUGIN_DB_USER', 'your_db_user');
define('MYPLUGIN_DB_PASSWORD', 'your_secure_password');
define('MYPLUGIN_DB_HOST', 'localhost');
– Access from your plugin:
$db_name = MYPLUGIN_DB_NAME;
—
#### 3. **Use a Custom Config File (Outside Web Root)**
– Create a separate PHP config file, like `/etc/myplugin-config.php`:
return [
'db_name' => 'your_db_name',
'db_user' => 'your_db_user',
'db_password' => 'your_secure_password',
'db_host' => 'localhost',
];
– Load it in your plugin:
$config = include('/etc/myplugin-config.php');
> Make sure the file path is not publicly accessible via the web server.
—
### β What to Avoid
– Hardcoding credentials inside plugin files (`.php`) in `/wp-content/plugins/`.
– Storing credentials in frontend-accessible JS or HTML.
– Committing sensitive credentials to version control.
—
Would you like a reusable helper function to load these securely inside your plugin?
—
## β Best Practice: External Config per Site (Not in Plugin)
### π Option 1: Define Constants in Each Siteβs `wp-config.php`
Modify each site's `wp-config.php` (outside the plugin and version control):
define('MYPLUGIN_EXT_DB_NAME', 'external_db_name');
define('MYPLUGIN_EXT_DB_USER', 'external_db_user');
define('MYPLUGIN_EXT_DB_PASS', 'external_db_password');
define('MYPLUGIN_EXT_DB_HOST', 'external-db-host.com');
Then, in your plugin:
$ext_db = new wpdb(
MYPLUGIN_EXT_DB_USER,
MYPLUGIN_EXT_DB_PASS,
MYPLUGIN_EXT_DB_NAME,
MYPLUGIN_EXT_DB_HOST
);
> β
**Pros**: Keeps credentials out of plugin files
> β
**Safe for distribution** β plugin doesnβt hold secrets
> β
**Flexible per site** β easy to change per environment
—
### βοΈ Option 2: Load from `.env` File (if using Bedrock or similar)
If the sites use Bedrock or Dotenv setup:
**In `.env` per site**:
“`dotenv
MYPLUGIN_EXT_DB_NAME=external_db_name
MYPLUGIN_EXT_DB_USER=external_user
MYPLUGIN_EXT_DB_PASS=secure_password
—
## β Solution: External Config File Loaded by Plugin
### π Option 1: External Config File (per site, outside plugin)
1. **Ask each site to place a file like this** (e.g., in `wp-content/` or a non-web-accessible directory):
**Path (example):**
`wp-content/myplugin-db-config.php`
**Contents:**
return [
'db_name' => 'external_db_name',
'db_user' => 'external_user',
'db_password' => 'secure_password',
'db_host' => 'external-host.com',
];
2. **In your plugin code**, check for the file and load credentials:
“`php
$config_path = WP_CONTENT_DIR . '/myplugin-db-config.php';
if (file_exists($config_path)) {
$config = include $config_path;
$ext_db = new wpdb(
$config
—
## β Final Approach: Load External DB Credentials from Config in Plugin
### π§ Step-by-Step Implementation in Your Plugin
#### π 1. **Site Admins Create Config File (Not Part of Plugin)**
Instruct each site owner to create this file **outside the plugin directory**, ideally in a safe location like:
wp-content/myplugin-db-config.php
With contents:
<?php
return [
'db_name' => 'your_external_db',
'db_user' => 'your_user',
'db_password' => 'your_password',
'db_host' => 'your-db-host.com',
];
> π This file is not version-controlled and can be safely ignored in backups if needed.
—
#### π¦ 2. **In Your Plugin, Load Config if Present**
In your pluginβs main file or service:
“`php
function myplugin_get_external_db() {
$config_path = WP_CONTENT_DIR . '/myplugin-db-config.php';
if (!file_exists($config_path)) {
error
If you're asking:
> π§© *Can we fully handle external DB credentials **inside the plugin itself**, without requiring any edits to `wp-config.php` or uploading extra files?*
Then the short answer is:
—
### β **No, not securely.**
Including external database credentials directly inside your **plugin code** (even via settings in `wp-admin`) means:
– π **Credentials are visible in plugin files** (dangerous if site gets compromised or the plugin is shared).
– π **Anyone with admin access** to a site can view/edit those credentials.
– β It violates separation of sensitive config from code β **a security best practice**.
—
### β But… here's what **you *can* do inside the plugin**, realistically:
—
## π Option 1: Allow Setting Credentials via Admin Settings Page (Not Ideal for Secrets)
You can create a settings page under `Settings β External DB` where site owners input:
– External DB Host
– DB Name
– DB User
– DB Password
You store them using `update_option()`:
update_option('myplugin_ext_db_host', sanitize_text_field($_POST['db_host']));
Then retrieve:
$ext_db = new wpdb(
get_option('myplugin_ext_db_user'),
get_option('myplugin_ext_db_password'),
get_option('myplugin_ext_db_name'),
get_option('myplugin_ext_db_host')
);
> π΄ **WARNING**: These values are stored in plain text in the database, and are not safe from admin users or plugin conflicts.
—
## β Recommended Hybrid Solution
If **you must keep it inside the plugin**, consider this secure-ish pattern:
1. **Check for `myplugin-db-config.php` in `wp-content`** first.
2. **If not found**, **fallback to admin settings** or throw a warning.
function myplugin_get_db_credentials() {
$config_file = WP_CONTENT_DIR . '/myplugin-db-config.php';
if (file_exists($config_file)) {
return include $config_file;
}
// fallback (less secure)
return [
'db_host' => get_option('myplugin_ext_db_host'),
'db_name' => get_option('myplugin_ext_db_name'),
'db_user' => get_option('myplugin_ext_db_user'),
'db_password' => get_option('myplugin_ext_db_password'),
];
}
Then:
$creds = myplugin_get_db_credentials();
$ext_db = new wpdb($creds['db_user'], $creds['db_password'], $creds['db_name'], $creds['db_host']);
—
## π Summary
| Approach | Secure? | Requires Site Owner Action? | Plugin-only? |
|—————————–|———|——————————|————–|
| Hardcoding creds in plugin | β No | β No | β
Yes |
| Admin settings in plugin | β οΈ Medium | β
Yes (they input creds) | β
Yes |
| External config file | β
Yes | β
Yes (upload file once) | β No |
| `wp-config.php` constants | β
β
Yes | β
Yes (edit config) | β No |
—
Would you like a ready-made admin settings page + DB connection code in your plugin?