0

Consider from the view point of wev developer, a public running site, whose code is to be made public but some data transactions on the site occur via php to MySQL server.

Code like this is usually,

 <?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?> 

placed in a file connect.php which is used to initiate connections.

  1. What would be the best way to prevent public access to this file's content over GitHub public repo.

  2. If in case .gitignore is used to remove the file from the repo, can we still keep the repo in sync with the webserver's serving directory.

Would like to know what would be the recommended way.

Dharman
  • 30,962
  • 25
  • 85
  • 135
ankit7540
  • 315
  • 5
  • 20

1 Answers1

1

You are approaching this problem from the wrong side. The solution is to never put confidential information into Git or any other VCS.

Don't hardcode the username and password. The whole reason why you have it in a variable is because these details should be variable and come from outside the file.

There are two generally recommended practices:

  1. Store username and password in environment variables. Using environment variables in PHP is quite easy and it ensures these values are outside your VCS.
  2. Store username and password in a config file outside of your web root directory. The config file can either be a PHP file or INI file. The important thing is not to include it in VCS and don't put it in a place accessible from the internet. You can then include the file or use parse_ini_file() to get the configuration settings. If you can you might also include it in the virtual host config file.

On another note:

Your code is vulnerable to credential leaking anyways. Never check for MySQLi connection errors manually. Please read Should we ever check for mysqli_connect() errors manually?

The correct way of connecting using MySQLi is this:

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', $env_dbusername, $env_dbpassword, 'db_test');
$mysqli->set_charset('utf8mb4'); // always set the charset

If you can, avoid MySQLi and use PDO instead.

Dharman
  • 30,962
  • 25
  • 85
  • 135
  • Could you add documentation links for both options mentioned. I did not know of above techniques. (I hardcoded !!) – ankit7540 Mar 30 '20 at 10:46
  • mysqli documentation is horrifyingly bad. I would not recommend relying on it. There is a little bit written here: https://www.php.net/manual/en/mysqli.quickstart.connections.php and here https://www.php.net/manual/en/mysqli.configuration.php – Dharman Mar 30 '20 at 10:51