Hiding DB Credentials WP

User
Can we hide db credentionals exernal from wordpress plugin
Assistant
Yes, you **can and should** hide your **database credentials** externally from a WordPress plugin for better **security and maintainability**. Here are some recommended ways to do this:

### βœ… 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?

User
but we have custom plugin that have distributed to multiple wordpress site and db used in plugin is same for all wordpress site means it is external db how hide
Assistant
Got it β€” since your **custom plugin is distributed across multiple WordPress sites**, and it connects to a **shared external database**, here's how you can **securely hide and manage those DB credentials** without hardcoding them into the plugin itself:

## βœ… 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

User
We have no option for edit each site wp-config
Assistant
Thanks for the clarification β€” if you **cannot edit `wp-config.php`** on each site but still want to **hide external DB credentials from your distributed plugin**, here are **secure alternatives**:

## βœ… 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

User
I need to it in our custom plugin
Assistant
Perfect β€” since you're distributing a **custom WordPress plugin** that connects to the **same external DB across many WordPress installs**, and you can't edit `wp-config.php`, here's a **clean way to implement this logic directly in your plugin**, while still hiding the credentials on a per-site basis.

## βœ… 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

User
Is anything we can do it in plugin itself
Assistant
Great question β€” and thanks for the clarification.

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?

Leave a Comment

Your email address will not be published. Required fields are marked *