Skip to content
PHP Logo

How should database credentials be securely stored and utilized in PHP scripts?

Database credentials should be securely stored in a separate configuration file outside of the web root directory. This file should define constants for the database host, username, password, and database name. These constants can then be included in PHP scripts that require database access, ensuring that the credentials are not exposed in the source code.

php
// config.php
define('DB_HOST', 'localhost');
define('DB_USER', 'username');
define('DB_PASS', 'password');
define('DB_NAME', 'database_name');

// database.php
require_once('config.php');

$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}