Mysql connect - does a username / password need to be hard-coded?

I am an iPhone developer, and I just started with PHP and mysql (website development for others and web services for my applications).

Whenever I hardcoded my username and password into a PHP file to connect to the database, I felt a little strange. Example:

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

I find this a bit uncomfortable if I ever have to show the code to anyone.

  • Is it safe or good practice?
  • Is there any other way to connect to the database?

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

+6
source share
2 answers

For the scenarios that will be redistributed, it would be better to group them together and either have 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 wasting money through code to find where any connections are made, etc.

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

+5
source

I never encode login information into PHP code. I always put it in a separate file, which is included in the actual PHP code file. This way, you never need to show login data to anyone. And getting a file a little harder if someone is trying to fake a web server.

+2
source

Source: https://habr.com/ru/post/895508/


All Articles