Question

I'm working on a small web project with a friend. It involves a lot of MySQL queries, so I've created a ConnectToDatabase() function that connects to the server and selects our database.

It looks something like this:

function ConnectToDatabase()
{
    mysql_connect("db.myawesomehost.com", "Bob", "correcthorsebatterystaple");
    mysql_query("USE BobDB;");
}

It feels really bad to hard-code our credentials like this. I can't think of any other way to handle it, though. Putting it in a constant doesn't really solve anything, and hiding it away in some text file just seems ridiculous.

Should I even care? How is this handled in large projects with tons of people?

Was it helpful?

Solution

Factor it out into a separate config file. For one, it'll let you at the very least set some variable like "DEBUG_MODE" that will switch out your production credentials for your test environment ones. You can optionally not keep the separate file under version control if you like, or keep one with dummy credentials in your code repository so that users have to supply their own credentials instead of having access to global ones.

OTHER TIPS

You should not hard code any credentials. Best thing is to read from a configuration file and cache them. Even in that case you better not put credentials in clear text - we need to encrypt the credentials in configuration files. At WSO2 all the credentials we read from configuration files are kept encrypted and use an approach called Secure Valut [a generic approach] to read those encrypted credentials and provide in clear text to the required application...

Thanks...

Typical rails configuration has usernames and passwords stored in a file.

It seems reasonable to split them out so that you can share code without sharing machine specific information. This is useful for multiple developers who have more than one user for their dev DB.

Reading from a file shouldn't be that much of a burden, particularly a file of some format: xml, json, yaml, ...

As the other answers suggest, most large projects hard code the username and password somewhere in the project, usually in a configuration file. I have never seen any that do it another way, however in the specific case that non-logged-in users do not need database access, it is possible encrypt the DB credentials and use everyone's password as a passphrase to decrypt them. Another drawback is if the user forgets their password, they won't be able to recover it without admin intervention and all existing users would need their passwords to be reset.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top