Path Inclusion/Global variable not working? - php

Simply put, my config file includes my database class, and the config file has in it:
global $db;
$db = new database(DB_HOST, DB_NAME, DB_USER, DB_PASS);
That file is root/config.php
Moving on to root/functions/func.newpage.php doesn't have any includes/requires, and uses $db->classfunction since the file I'm working with:
root/newpage.php - requires the config file, as well as func.newpage.php.
However I still come up with: Undefined variable db.
Anything you guys are seeing I'm not? Thanks! Let me know if more details are needed.

Are you doing this global $db inside of a function? If not, remove that line, because global is used to add an existing global variable to the scope of a function.
Anyway, if you want to make sure that you're including the config file, you could add an echo("config") at the top of the config script, and you'll be sure that it was included right.
Good luck!

Related

Override core Magento DB connection using environment variables

I am trying to use environment variables that are loaded into my Magento application to override the default database connection credentials.
I've managed to 'almost' get this working using the getenv('MY_CUSTOM_VAR'), however I am trying to use this same method to override the database credentials, so this sensitive data can be stored within the htaccess.
e.g
# .htaccess file
SetEnv DB_USERNAME root
SetEnv DB_PASSWORD password123
SetEnv DB_HOST localhost
My App.php (within app/code/local/Mage/Core/Model/App.php - a copy of the one from the core pool)
// my function that overrides the core one
protected function _initBaseConfig()
{
Varien_Profiler::start('mage::app::init::system_config');
$this->_config->loadBase();
/* Read DB connection config from environment variables */
$connection = $this->_config->getNode('global/resources/default_setup/connection');
$connection->setNode('host', getenv('DB_HOST'));
$connection->setNode('username', getenv('DB_USERNAME'));
$connection->setNode('password', getenv('DB_PASSWORD'));
Varien_Profiler::stop('mage::app::init::system_config');
return $this;
}
I want the $connection just created to be the default global database connection used site-wide, this code should appear to do that but if i enter pure random entries for DB_HOST/DB_PASSWORD etc.. it still connects to the database which suggests that it isn't overriding the default database settings configured with the Magento setup.
Any ideas on how to get this $connection to override and become the 'global' database connection?
P.S Apologies in advance if this question is similar to my previous one, the original question was a bit of a general question whereas this one is much more focused to particular section.
Update...
I have open the local.xml within the app/etc directory and set the 'default setup' database connection to inactive (by changing the active node value to 0) and this as expected returns an error. It would appear the overriding function doesn't seem to like to override the initial db connection.. any ideas guys?
For MySQL db you can do next:
Copy file lib/Zend/Db/Adapter/Mysqli.php to app/code/local/Zend/Db/Adapter/Mysqli.php
Open app/code/local/Zend/Db/Adapter/Mysqli.php and find _connect() function.
In this function near line 317 you'll see:
$_isConnected = #mysqli_real_connect(
$this->_connection,
$this->_config['host'],
$this->_config['username'],
$this->_config['password'],
$this->_config['dbname'],
$port
);
Redefine params:
$this->_config['host'] = getenv('DB_HOST');
$this->_config['username'] = getenv('DB_USERNAME');
$this->_config['password'] = getenv('DB_PASSWORD');
$_isConnected = #mysqli_real_connect(
$this->_connection,
$this->_config['host'],
$this->_config['username'],
$this->_config['password'],
$this->_config['dbname'],
$port
);
Clear cache and restart MySQL. For other databases check files in lib/Zend/Db/Adapter folder (DB2.php, Oracle.php, Sqlsrv.php).

PHP Function Scope Failure

I am struggling to understand scope and what's preventing my new code from working (assuming it is a scope issue).
The following function is in a file PATH.'/includes/custom-functions.php' that references a class:
function infusion() {
require_once(PATH.'/classes/infusion.php'); //PATH is defined in WordPress from ~/wp-content/themes/theme/
return new infusion();
}
The class is reliant on PATH.'/api/isdk.php' and connection credentials from another file within /api/ directory. From within PATH .'/includes/custom-functions.php', I have many other functions that call $infusion = infusion(); and work perfectly.
PROBLEM
I have created a new file: PATH.'/includes/report.php' which I need to access $infusion = infusion();but can't get to work by either repeating the function infusion() definition from above; using require_once();; or using include();. All 3 of those options simply kill the rest of the code and I can only come to the conclusion - well, I have no conclusion.
Any help would be greatly appreciated.
I'm assuming the code isn't using namespaces, therefore you aren't permitted to redeclare the infusion function (either by redefining the function, or re-including the class).
Your includes/report.php file should simply have:
require_once PATH.'/includes/custom-functions.php';
// your other code here ...
$infusion = infusion();
It may be the case that other files / classes that you're including in your file are already requiring custom-functions.php along the line, so you may be able to skip that entirely. Also note that the PATH constant should have already been defined somewhere (either directly or via an included file) before you attempt to use it. If you set your error_reporting to include E_ALL, you'll get a notification in your error log if that constant doesn't exist.
If that fails, your error log(s) may provide some additional background on what your issue is.

Is there a way to get the name of the top level PHP file from inside an included one?

Let's say I'm writing a global logData method that wants to write to a log file that has the same name as the php that's running it, but with a .log extension.
I'm including this logging in a parent php with the intention of having it always write to log files that are whatever the *parent file name is (not the tools.php lib in which it's sitting).
So, I have
/some/arbitrary/directory/parent.php
which calls
include ("/path/to/my/php/libs/tools.php");
but when I run my logging method that's in tools.php it logs to a file called
/path/to/my/php/libs/tools.php.log
rather than
/some/arbitrary/directory/parent.php.log (which is what I'd like).
I'm using __FILE__ which is behaving this way (probably as its intended to). Is there a command for getting the parent's file name so that I can get this to work as I intend? Or will I have to pass FILE as a param into my method from the parent php to get it to write to the correct output file?
TIA
You could probably use $_SERVER["SCRIPT_FILENAME"]
debug_backtrace() will give you what you need.
http://php.net/manual/en/function.debug-backtrace.php
You need to pass __FILE__ to the log class.
Something like:
// file:/some/arbitrary/directory/parent.php
$logger = new Logger(__FILE__);
// file:/path/to/my/php/libs/tools.ph
public function __construct($file) {
// But it is not good idea to save log file same with php files.
$this->log_path = $file.'.log';
}

Defining Application Constants in Codeigniter

I want to know a clean way of defining Application Constants in Codeigniter. I don't want to change any native file of codeigniter. Hence I don't want to define it in application/config/constants.php as when I need to migrate to newer version of code-igniter I will not be able to copy the native files of codeigniter directly.
I created a file application/config/my_constants.php and defined my constants there. 'define('APP_VERSION', '1.0.0');'
I loaded it using $this->load->config('my_constants');
But I am getting a error
Your application/config/dv_constants.php file does not appear to contain a valid configuration array.
Please suggest me a clean way of defining application level constants in code-igniter.
Not using application/config/constants.php is nonsense! That is the only place you should be putting your constants. Don't change the files in system if you are worried about upgrading.
just a complete answer. (None of the answers show how to use the constants that were declared)
The process is simple:
Defining a constant. Open config/constants.php and add the following line:
define('SITE_CREATOR', 'John Doe')
use this constant in another file using:
$myVar = 'This site was created by '.SITE_CREATOR.' Check out my GitHub Profile'
Instead of using define(), your my_constants.php file should look something like this:
$config['app_version'] = '1.0.0';
Be careful with naming the array key though, you don't want to conflict with anything.
If you need to use define(), I would suggest doing it in the main index.php file, though you will still need to use APP_VERSION to get the value.
config file (system/application/config/config.php) to set configuration related variables.
Or use
constant file (system/application/config/constants.php) to store site preference constants.
=======================
DEFINE WHAT YOU WANT
=======================
$config['index_page'] = 'home';
$config['BASEPATH'] = 'PATH TO YOUR HOST';
Please refer this:
http://ellislab.com/forums/viewthread/56981/
Define variable in to constants & add value on array
$ORDER_STATUS = array('0'=>'In Progress','1'=>'On Hold','2'
=>'Awaiting Review','3'=>'Completed','4'
=>'Refund Requested','5'=>'Refunded');
You can accomplish your goal by adding constants to your own config file, such as my_config.php.
You would save this file in the application/config folder, like this:
application/config/my_config.php.
It is very common to have a separate config file for each application you write, so this would be easy to maintain and be understood by other CI programmers.
You can instruct CI to autoload this file or you can load it manually, as needed. See the CI manual on "Config class".
Let me suggest that you use composer.json to autoload your own Constants.php file, like this:

safest place to store php values for msql_connect?

Were is the safest place to store my values which will be used in mysql_connect also what is the safest way to call these variable would be better using a require , include or something else ?
thanks :)
The best place to store it IMO is in a PHP file (whether you use require or include to fetch it doesn't matter) outside the web root, i.e. not directly accessible in the browser.
<?php
$db_server = "xyz";
$db_user = "def";
$db_password = "abc";
?>
If there is no access outside the web root
#Yacoby wrote this down in his answer. He deleted it since, but it definitely deserves mention.
There are foolish hosting providers who don't allow access outside the web root. In that case, you put the config file in a directory in your web site and protect it using a .htaccess file containing Deny from All. This works on most hosting packacges. Make sure you test it though, you should get a 403 Forbidden when trying to access that file.
This is what I usually do:
Set up the project so the website is a subfolder of the project. That way you can have all PHP classes and config files outside the web root folder.
Have a config.php file with an array of Database credentials. For example:
$databases = array(
"read" => array("host" => "127.0.0.1",
"user" => "read",
"pword"=> "secret",
"dbase"=> "projectName"));
Extend the PDO class (or create a new class) called Database that has a constructor taking one argument.
class Database extends PDO{
function __construct($database){
global $databases;
$db = $databases[$database];
parent::__construct("mysql:dbname=".$db['dbase'].";host=".$db['host'],
$db['user'], $db['pword']);
}
}
Now you can pass the array key to one of the database credentials as an argument to the Database class constructor, and then it will sign in with those details. This means that you can have several users to access the database (one for reading, and one for writing).

Categories