I'll try to elaborate on the other solutions you likely found on the forum, since you said you didn't really understand them.
Remember that (assuming your webserver is properly configured), your PHP source code is not accessible externally (i.e., not accessible to your visitors). So there isn't actually anything intrinsically wrong with storing your credentials in your source code. The main problem is if you're sharing the source code with anyone else, for instance on Bitbucket or Github. Additionally, anyone with file access to your server (e.g., someone who can sit down at the computer, or who can get a remote shell into it) will be able to read these.
The standard approach is to just setup a config file which is not part of the codebase (i.e., it is not put under version control and not shared without anyone else who may be using or developing the code). So it would look something like this:
<?php
$db_host = "localhost";
$db_username = "blahblahblah";
$db_password = "whatever";
$db_name = "dbname";
?>
And so on for any other configuration values you need. You could store this in, say, config.php
and for added security, place it outside of your webserver's document root. That way there's no way it can be accessed from the web. You also want to make sure it is only readable by the user account which will be executing your script, often web
or www
or apache
.
Now when you need the config values, you can just include("config.php")
and access the variables directly. For instance, it might look something like this:
<?php
class Database{
public function __construct(){
require("config.php");
$this->con = new mysqli($db_host, $db_user, $db_password, $db_name);
}
}
?>
Notice I require
'd the config file inside the function: this is just a little added security to ensure that the variables in the config file only have function-local scope and are no longer accessible once the function returns.