2

Is there a more secure or standard way to access your mysql db via php then explicitly writing your credentials like the following...

$servername = "localhost";
$username = "user1";
$password = "pass1";
$dbname = "test-db";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

If so, any ideas where to find more information and study up on the subject?

1
  • Which server are you using for this? Commented May 3, 2016 at 2:52

1 Answer 1

2

Move it into an environment file, preferable the apache environment file, if you are on a LAMP stack.

<VirtualHost hostname:80>

SetEnv mysqllogin user
SetEnv mysqlpassword secret

</VirtualHost>

Then you can access it in PHP like so.

apache_getenv('mysqlpassword')
Sign up to request clarification or add additional context in comments.

3 Comments

This is a good method because the permissions on the apache config file are stricter than on your php files. You might also want to consider using different mysql users with limited privileges. Eg, if a php page page only selects data from one table, set up a user with just those privileges. Then, even if somehow you got SQL-injected, the most that can happen is a select from that table.
I think i'll look into doing the apache environment file, but in the meantime creating a limited user is clever. thanks.
Apache env takes little time, and remember if you are running your code with github or similar it is not always fun having passwords floating around. Bonus point, normally i would limit the mysql server to only accept local requests, so then even if they have username and password nothing can happen

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.