Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql connect - should username/password be hardcoded?

I'm an iPhone developer, and I've just started out with PHP & mysql (making websites for others, and web services for my apps).

Whenever I hardcoded my username and password into a PHP file to connect to the database I felt a bit odd. Example:

$con = mysql_connect('localhost:8888','root','password');

I find this slightly awkward if I ever have to show code to anybody.

  • Is this secure or good practice?
  • Is there another way I should be connecting to the database?

I would be very grateful for any advice related to this issue.

like image 540
Alex Coplan Avatar asked Aug 20 '11 21:08

Alex Coplan


People also ask

What is default MySQL username and password?

The default user for MySQL is root and by default it has no password. If you set a password for MySQL and you can't recall it, you can always reset it and choose another one.

Why are usernames considered just as important as passwords MySQL?

This means that anyone can attempt to connect to the server using any user name, so you cannot make a database secure in any way unless all MySQL accounts have passwords. Anyone who specifies a user name for an account that has no password can connect successfully to the server.

Where are MySQL user passwords stored?

MySQL stores credentials in the user table in the mysql system database. Operations that assign or modify passwords are permitted only to users with the CREATE USER privilege, or, alternatively, privileges for the mysql database ( INSERT privilege to create new accounts, UPDATE privilege to modify existing accounts).


2 Answers

For scripts that are going to be redistributed it would be better to group these together and either have them as constants or variables.

config.php

<?PHP
define('DBHOST', 'localhost');
define('DBPORT', '8080');
define('DBNAME', 'my_db_name');
define('DBUSER', 'root');
define('DBPASS', 'password');

db.php

<PHP
include('config.php');
$con = mysql_connect(DBHOST.':'. DBPORT,DBUSER,DBPASS);
mysql_select_db(DBNAME, $con);

Doing this will make it easier for someone to make changes in the future instead of having to trawl through code to find where any connections are made etc.

For slightly better security the config.php script could be placed outside of the doc root so that it cannot be called directly.

like image 91
Peter Avatar answered Oct 26 '22 21:10

Peter


I never hardcode the login information into the PHP code. I always put it in a separate file that gets included into the actual PHP code file. That way you never need to show the login data to anyone. And makes it slightly harder to get at the file if someone is trying to spoof the web server.

like image 27
Flyingdiver Avatar answered Oct 26 '22 22:10

Flyingdiver