In teaching myself PHP, I have come against a bit of a concern around security. I would very much appreciate some input on the two options below. Likely they are both wrong, although both work... But I would prefer to build on a proper solution.
I referenced this, and they indicate a few other options, but it is from 7 years ago... I also looked at this, but I am not understanding a single thing in that detailed answer!
The idea is to place all my variables inside a JSON file named global.json in order for Puppet to maintain changes in hostnames, passwords, API tokens etc. So it is fairly sensitive information.
The global.json file is protected via a Directory directive.
It is instantiated via a variables.php file:
<?php
$data = file_get_contents('includes/global.json');
$config = json_decode($data);
// Database Variables
$database_host = $config->{'database'}->{'host'};
$database_user = $config->{'database'}->{'username'};
$database_password = $config->{'database'}->{'password'};
$database_name = $config->{'database'}->{'database'};
$database_port = $config->{'database'}->{'database'};
?>
My main question is around the database functions.
Before I used a JSON file, I would include a dbcontroller file:
class DBController {
private $host = "192.168.50.3";
private $user = username;
private $password = password;
private $database = database_name;
private $port = 5432;
private $conn;
function __construct() {
$this->conn = $this->connectDB();
}
function connectDB() {
$conn = pg_connect("host=$this->host dbname=$this->database user=$this->user password=$this->password");
return $conn;
}
function runQuery($query) {
$result = pg_query($this->conn,$query);
$resultset = pg_fetch_all($result);
if(!empty($resultset)) {
return $resultset;
}
}
}
But, using the JSON file, I 'have' to update that to:
class DBController {
private $conn;
function __construct() {
$this->conn = $this->connectDB();
}
function connectDB() {
require_once 'includes/variables.php';
$conn = pg_connect("host=$database_host dbname=$database_name user=$database_user password=$database_password");
return $conn;
}
function runQuery($query) {
$result = pg_query($this->conn,$query);
$resultset = pg_fetch_all($result);
if(!empty($resultset)) {
return $resultset;
}
}
}
Is the implementation I use via JSON, (by including the file in the connectDB function) an accepted or at least a proper way to do this?
I suspect a first step will be to place the globals.json file outside the doc root rather than jsut rely on the directive, but any other advise or recommendations?