How can I avoid hardcoding the database connection password? - php

I am working on a school-project (writing a website) and I ran into the problem of providing the password for the connection to our database. Because of our Open-Source license we have to publish the sourcecode but that would mean that everyone could connect to the database and see tha data.
Currently our connection (a php file) looks like this:
$host="************";
$password="************";
$this->conn = new mysqli($host, $user, $password, $dbname).mysqli_connect_error());
Now my question is: how can i provide the password to connect to the database without needing to write $password=... ?

Ok, here's the one with the ini file:
xxx.php
<?php
$db_params = parse_ini_file( dirname(__FILE__).'/db_params.ini', false );
// .....
$this->conn = new mysqli($db_params['host'], $db_params['user'], $db_params['password'], $db_params['dbname'], $db_params['port'], $db_params['socket']).mysqli_connect_error());
// ...
?>
db_params.ini
host=mysql.example.com
port=3306
socket=
user=testuser
password=myPasswort
dbname=myDatabase

Use a single file to contain your configuration variables and exclude this file when sharing your code.
For example:
require_once('config.php');
$this->conn = new mysqli($config['db']['host'], $config['db']['user'], $config['db']['pass'], $config['db']['dbname']);
The config.php file would include:
$config['db']['username'] = 'user';
$config['db']['password'] = 'pass';
...
You could/should expand this to include the host, port, database name etc.

Related

Unable to get variables from different files

Im trying to get data from my database and echo it with a variable, but I have a problem with that. When I try to get my variables from different files it shows me this error:
Undefined variable: con in.
Here some codes:
Code from functions.php:
include "authentication.php";
function GetData() {
$id = session_id();
$result3 = mysqli_query($con,"SELECT * FROM accounts where id='$id'");
while($row3 = mysqli_fetch_array($result3));
{
$email=$row3['email'];
$fullname=$row3['fullname'];
$usualname=$row3['usualname'];
$lastname=$row3['lastname'];
}
}
Code from authentication.php:
$DATABASE_HOST = 'localhost';
$DATABASE_USER = '***';
$DATABASE_PASS = '***';
$DATABASE_NAME = '***';
$con = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS, $DATABASE_NAME);
if ( mysqli_connect_errno() ) {
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
This also happens when I try to get variables from other files..
Here you get some screenshots of the error from different files and different variables:
Both files are in the same directory called PHPscripts:
This looks like a problem of scoping.
Remember that in PHP, variables in the global scope cannot be accessed from a function. You must explicitly do something like global $con; inside the function GetData() before you try to access $con.
From a system design point of view this isn't the best approach. It will make it hard to keep track of your variables. You won't know who (which part of your script) is accessing that global and you won't know how it is being modified or in what order. This can lead to some bugs that are very difficult to identify.
require_once dirname(__FILE__) . auth.php;
Require_once or require with Unix full path works like a charm. Replace include stroke in your code.

Combining php strings

I have two files, one config.php and source.php in a subdirectory. In the config file I have something that looks like this
<?php
//app settings
$GLOBALS['app_url'] = 'http://www.website.com/subdirectory'; //ex:
//demo mode
$GLOBALS['demo_mode'] = 0; //possible values: 0 or 1
$GLOBALS['db_table']['sms'] = 'sms_numbers';
$GLOBALS['db_table']['sms_history'] = 'sms_history';
?>
In the config.php file, I have this string $GLOBALS['app_url'] = 'http://www.website.com/subdirectory'; for the base URL and I'd like to make it so that the base URL is automatically detected. I'd like to use something similar to this <?php echo "http://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']; ?>. I'm using these files under different directories and that's why I'd like to combine them in order to make it automatic without me having to update the base URL manually every time I create a new subdirectory.
Also, inside config.php I have:
//Admin access
$GLOBALS['admin_username'] = 'admin';
$GLOBALS['admin_password'] = 'password';
These values are not in a database but a local file named source.php and I'd like to be able to update the values "admin" and "password" from this source.php file.
Inside the source.php file I guess I'd have to have something thta'd look like this: $username = 'admin';
I'm really sorry but I'm new and would like to learn this stuff. I appreciate any help I can get.
Thank you
Use global constants in config.php
define('APP_URL', 'http://www.website.com/subdirectory');
Then anywhere in the code you can do:
$path = APP_URL . "/path/to/file"
I dont recommend storing admin_username and admin_password as global variables or constants, instead you can create a class in your config.php that contains the values.
Config Example:
config.php
define('APP_URL','http://www.website.com/subdirectory');
define('DEMO_MODE',0); //possible values: 0 or 1
.....
class DB{
var $conn;
public function __construct()
{
$user = "admin";
$pass = "pass";
$host = "127.0.0.1";
$database = "database_name";
$this->conn = mysqli_connect($host, $user, $pass, $database);
}
}
Then in your index.php file you do:
require_once("config.php")
$db = new DB;
$conn = $db->conn();
....

Absolute URL on localhost and web server for YII Framework?

I am using YII2 framework in netbeans, every time my project is deployed to the web server I have to change the url to that of the web server from localhost.
Therefore,
Created a config.php file in the controller folder
define("LOCAL", "http://localhost");
define("WEB", "http://website.com");
global $environment;
$environment= LOCAL; //change to WEB if you're live
Every file that needs it, put this at the top
include_once(dirname( __FILE __)."/config.php");
and every time the url is needed in the code call it using
echo $environment;
But I get the error that $environment is not defined.
What am I doing wrong?
Reference How to implement absolute URLs on localhost and web server?
Create db_config.php file in you config folder like below -
define('DB_NAME', '');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
after that - if you want to access that global variables then user like this -
create new function for connection in your controller
private function connectToDb($db_name) {
include Yii::getAlias('#app') . "/config/db_config.php"; // Include db_config.php file
$connection = new \yii\db\Connection([
'dsn' => 'mysql:host=' . DB_HOST . ';dbname=' . $db_name,
'username' => DB_USER,
'password' => DB_PASSWORD,
]);
return $connection;
}
After that call above function from anywhere from controller like below -
$super_conn = $this->connectToDb('my_db_name');
$super_conn->open();
$sql = "select * form student where id = 1"; //your query
$super_conn->createCommand($sql)->execute();
thank you..
hope this will help...

Require_once doesn't seem to affect all functions?

Everything was working fine in my little project, until I decided to clean up a little bit and moved database-related php-files to their own folder. Then things went strange.
I am trying to use two functions here:
function getEntries () {
require_once("mysqliVariables.php");
$mysqli = new mysqli($dbHost, $dbUname, $dbPwd, $dbName);
$sql = "statement...";
$result = $mysqli->query($sql) or die($mysqli->error);
echo $dbHost; // prints host
return $result;
}
function getBiggestMonth () {
require_once("mysqliVariables.php");
$mysqli = new mysqli($dbHost, $dbUname, $dbPwd, $dbName);
echo $dbHost; // prints nothing! why?
$sql = "statement...";
$result = $mysqli->query($sql) or die($mysqli->error); // this line does not run, of course.
return $result;
}
I use another function in a different file (and folder) to call these functions, that starts like this:
function listTasks() {
require_once("db/mysqliFunctions.php");
// Get entries using mysqli.
$tasks = getEntries();
echo "<pre>";
var_dump($tasks);
echo "</pre>"; // program works fine this far.
$bm = getBiggestMonth(); // program breaks somehow during this function call.
My variables are in a php-file like so:
<?php
$dbHost = "host";
$dbUname = "username";
$dbPwd = "password";
$dbName = "databasename";
?>
If I switch the funtion's call order, then getBiggestMonth() runs fine and the other one won't. Also, all of this worked fine when all the files were located in the same folder (the functions were then static functions inside a class, but that shouldn't be an issue, the same problem persists here), so I dont understand how possible variable scope can be different here, and require_once should take care of other things. Help?
This is because you are using require_once. It will only include the configuration once. You can change it to use require so that it will work as you expect.
The require_once() statement is identical to require() except PHP will
check if the file has already been included, and if so, not include
(require) it again.
You are using require_once to pull in a file into the scope of the getEntries() function. PHP keeps a record of the files that have been required in so when you then call require_once in getBiggestMonth() it knows it has already been included in getEntries(). Because it has already been included it does not require the file in again so you don't get your variables in your getBiggestMonth() scope.
require_once does not have anything to do with variables it just monitors the files that have been included into the current PHP process.
The echo statement after the return in getEntries() wont obviously work as the function exits after the return.

make db connection persistent throught zend framework

I'm using zend framework. currently everytime I need to use the db I go ahead and connect to the DB:
function connect()
{
$connParams = array(
"host" => $host,
"port" => $port,
"username" => $username,
"password" => $password,
"dbname" => $dbname
);
$db = new Zend_Db_Adapter_Pdo_Mysql($connParams);
return $db
}
so I would just call the connect() function everytime I need to use the db
My question is...suppose I want to reuse $db everywhere in my site and only connect once in the very initial stage of the site load and then close the connection right before the site gets sent to the user, what would be the best practice to accomplish this?
Which file in Zend should I save $db in, what method should I use to save it (global variable?), and which file should I do the connection closing in?
If you are using the default project structure (with the application, library, tests and public folders), you should use set up the db parameters in application/configs/application.ini
Example application.ini:
[production]
resources.db.adapter = "pdo_mysql"
resources.db.params.host = "localhost"
resources.db.params.username = "testuser"
resources.db.params.dbname = "testdb"
resources.db.params.password = "testpasswd"
resources.db.isDefaultTableAdapter = true
In this way zend framework will automatically open and close the connections to the database and you can use the Zend_Db_Table or Zend_Db_Table_Abstract classes to query your tables easily, for example, to retrieve the student's data for a given SSN you could write a model (application/models/Student.php) that looks something like this:
<?php
class Model_Student extends Zend_Db_Table_Abstract
{
protected $_name = "student";
public function fetchRowsBySSN($ssn)
{
$select = $this->select();
$select->where('ssn = ?', $ssn);
return $this->fetchRow($select)->toArray();
}
}
As you can see there's no need to open/close the connection and you get an associative array with the fields and values of the student record.
Your best best may be to move all of your db connection code into a separate class in which you can set a static $db var.
protected static $_db;
public static function connect()
{
if (self::$_db == null) {
$config = Zend_Config_Xml(); // whatever you'd use
self::$_db = Zend_Db::factory($config->database);
self::$_db->setFetchMode(Zend_Db::FETCH_OBJ);
self::$_db->query('SET NAMES UTF8');
Zend_Db_Table::setDefaultAdapter(self::$_db); // optional
}
return self::$_db;
}
public static function close()
{
if (self::$_db != null) {
self::$_db->closeConnection();
}
}
According to Zend:
Normally it is not necessary to close a database connection. PHP automatically cleans up all resources and the end of a request. Database extensions are designed to close the connection as the reference to the resource object is cleaned up.
However, if you have a long-duration PHP script that initiates many database connections, you might need to close the connection, to avoid exhausting the capacity of your RDBMS server. You can use the Adapter's closeConnection() method to explicitly close the underlying database connection.

Categories