Absolute URL on localhost and web server for YII Framework? - php

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...

Related

Including Config file in connection file not working

I'm creating a CMS that provides dynamic database creation at the initial project setup stage.
I have defined the database configuration details as constants in config.php file:
//Database Name
define('DEFAULT_DB_NAME', 'cms');
//User Name
define('DEFAULT_USER_NAME', 'root');
//Password
define('DEFAULT_PASSWORD', '');
//Host Name
define('DEFAULT_HOST_NAME', 'localhost');
I included the config.php file in my database connection file (db.class.php):
<?php
include_once '../../config/config.php';
class Db{
protected $conn;
protected $host = DEFAULT_HOST_NAME;
protected $username = DEFAULT_USER_NAME;
protected $password = DEFAULT_PASSWORD;
protected $dbname = DEFAULT_DB_NAME;
public function __construct(){
$this->conn = new mysqli($this->host, $this->username, $this->password, $this->dbname);
if($this->conn->connect_error){
die("<h3>Connection Failed!!! Error: " . $this->conn->connect_error . "</h3>");
}
}
}
I also have created a dynamic Style sheet (admintheme.php) that modifies the admin panel based on user preference:
<?php
header("Content-type: text/css;");
include_once '../../model/admintheme.class.php';
$theme = new Admintheme();
$result = $theme->ReadAdminTheme();
if($result == '' || $result == '0'){
$sidebarBg = "#111";
$sidebarPosition = "left";
$sidebarunset = "left";
$sidebarright = "unset";
}
else{
$row = $result->fetch_assoc();
$sidebarBg = $row['sidebarbg'];
$sidebarPosition = $row['sidebar_position'];
if($sidebarPosition == "left"){
$sidebarunset = "right";
}
else{
$sidebarunset = "left";
}
}
?>
/*-- ------------------------xx----------------------- */
/***** Content Section Starts *****/
.content{
margin-<?= $sidebarPosition; ?>: auto;
}
/***** Content Section Ends *****/
/**** Side Bar Section Starts *****/
.sidebar-nav{
background-color: <?= $sidebarBg; ?>;
<?= $sidebarPosition; ?>: 0px;
}
The issue is that when I use static data in "db.class.php" file (ex. directly write "localhost" in place of the constant and so on..) then "admintheme.php" works fine and displays the desired output, but when I use constants in place of the static data then all other functionalities of the project work fine and retrieve data from the database except "admintheme.php".
The "admintheme.php" also works fine when the constants are defined inside the "db.class.php" or if the "config.php" file is in the same directory as of the "db.class.php" but while including the the "config.php" file from other directory, all other data is retrieved except "admintheme.php".
**No direct error is received but in the browser's console, it states (include_once(../../config/config.php): failed to open stream: No such file or directory...)
**Included path is correct in both "db.class.php" and "admintheme.php".
Any help is greatly appreciated.
Adding "DIR" magic constant solved the issue.

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();
....

How can I avoid hardcoding the database connection password?

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.

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