存储MySQL凭据的安全方案:PHP引入database.php文件是否安全?
database.php File with Credentials Safe? Great question—this is one of the first security hurdles new PHP developers run into, so you’re thinking in the right direction!
Let’s break down your concern first: By default, if you place your database.php directly in your web root directory, there is a small but real risk of it being exposed as plain text. This happens if your web server misconfigures PHP parsing (e.g., mod_php isn’t enabled in Apache, or Nginx isn’t pointing to PHP-FPM). In that case, someone visiting yoursite.com/database.php would see your raw database username and password.
But the good news is there are simple, reliable fixes to make this setup safe:
Move the credentials file outside your web root
This is the most effective fix. Most web hosts structure your server like this:/your-server-folder/ /public_html/ (this is your web root—where index.php lives) /private/ (outside web root, not accessible via browser)Put your
database.phpin the/private/folder, then include it using an absolute path in your web-facing scripts:require_once(__DIR__ . '/../private/database.php');Since this folder isn’t mapped to your website URL, browsers can’t reach it at all.
Lock down file permissions
On Linux/Unix servers, set the permissions ofdatabase.phpto600(read/write only for the file owner). Run this command in your terminal:chmod 600 /path/to/your/database.phpThis ensures even if the file somehow ends up in the web root, other users (including potential attackers) can’t read its contents.
Ensure your server is configured to parse PHP files
Double-check that your web server treats.phpfiles as executable scripts, not static text. For Apache, make suremod_phpis enabled and you have aAddType application/x-httpd-php .phpdirective in your config. For Nginx, confirm your server block includes a location block that passes.phprequests to PHP-FPM.Use environment variables (advanced but recommended)
Instead of hardcoding credentials indatabase.php, store them in environment variables (e.g., a.envfile outside the web root). Then access them in your PHP script like this:$dbHost = getenv('DB_HOST'); $dbUser = getenv('DB_USER'); $dbPass = getenv('DB_PASS');This way, even if
database.phpis exposed, it won’t contain your actual credentials—just references to the environment variables.Bonus: Always use prepared statements
While this doesn’t fix the file exposure risk, it’s critical for overall database security. Use PDO or MySQLi prepared statements to prevent SQL injection attacks, which are far more common than file exposure incidents.
In short: As long as you follow the first three steps above, including a credentials file via require_once is a safe and standard practice in PHP development.
内容的提问来源于stack exchange,提问作者Retrospec

