PHP Object Constructor database connection -


i starting in oop using mysqli , came problem.

this code:

class database{   public $mysqli; public function __construct($db_host, $db_user, $db_password, $db_name){      $this->con = new mysqli($db_host, $db_user, $db_password, $db_name);    } } 

the code above working. when need instantiate class, need declare hostname, username , database name in main page not secure , vulnerable ( guess ).

     $db = new database("hostofdatabase", "dbroot", "", "databaseofmine"); 

i want ask if right way of putting database connection in class constructor. didn't understand other solutions found in forum though. hope enlighten me bit. cheers!

i'll try elaborate on other solutions found on forum, since said didn't understand them.

remember (assuming webserver configured), php source code not accessible externally (i.e., not accessible visitors). there isn't intrinsically wrong storing credentials in source code. main problem if you're sharing source code else, instance on bitbucket or github. additionally, file access server (e.g., can sit down @ computer, or can remote shell it) able read these.

the standard approach setup config file not part of codebase (i.e., not put under version control , not shared without else may using or developing code). this:

<?php  $db_host = "localhost"; $db_username = "blahblahblah"; $db_password = "whatever"; $db_name = "dbname";  ?> 

and on other configuration values need. store in, say, config.php , added security, place outside of webserver's document root. way there's no way can accessed web. want make sure readable user account executing script, web or www or apache.

now when need config values, can include("config.php") , access variables directly. instance, might this:

<?php class database{      public function __construct(){         require("config.php");         $this->con = new mysqli($db_host, $db_user, $db_password, $db_name);    } } ?> 

notice require'd config file inside function: little added security ensure variables in config file have function-local scope , no longer accessible once function returns.


Comments

Popular posts from this blog

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -