Correctly Storing DB Credentials In PHP
There’s a way to do things, and then there’s a right way to do things. If you’ve been accustomed to storing your database login credentials inside or adjacent to your public-facing web application, you may benefit from this quick read.
In this write-up, I will show you the recommended approach to take to securely store and access your database credentials when working with PHP.
The Config File
First thing is first: in this example, I am using my shared hosting plan, and I assume you are too. What this means is you will be storing your web files somewhere under the public_html directory, which makes it publicly accessible. Our goal is to make a “private” folder outside of public_html that will be inaccessibly publicly, but accessible by our application residing in “public_html”.

Inside the private directory, we will create a file called config.ini that will store these credentials.

Enter your database credentials in this config.ini file as follows (obviously replacing the values in quotations with your own values).
config:ini
[database]
servername = “localhost”
username = “test_user”
password = “test_p4ssw0rd!”
dbname = “test_db”
Integration
Now, we can work on our php application under the public_html directory and point to the config file to parse the database credentials. Alternatively, you can call this in a separate file and then include the separate file in your main php application file, but for this short example we’ll just call it from the app directly. For more information on the parse_ini_file function, you can refer to the php documentation here
app.php
$config = parse_ini_file(‘../private/config.ini’);
In the same file, we can use PDO and reference the elements of $config to build a connection string and query our database.
try{
$_DB = new PDO(“mysql:host={$config[‘servername’]};dbname={$config[‘dbname’]}”, “{$config[‘username’]}”, “{$config[‘password’]}”);$getIDs = $_DB->prepare(“Select * from employee_billing”);
$getIDs->execute();
$getEmpIDs = $getIDs->fetchAll();foreach ($getEmpIDs as $emp){
echo “{$emp[’employee_id’]}
“;
}
}
catch (PDOException $e) {
die(“Error – connection failed. Please check your credentials or contact your administrator.”);
}
And this is all it takes to get your data to appear!

If you followed along, we just stood up a php application that uses a private, secure config file to supply its database credentials for connectivity.