What's the best way to setup configuration variables in a script? Like base_directories, user, passwords for db connect, etc.? So that all functions have access to them. Is it better to set this file up and then pass the variables one by one?
| SitePoint Sponsor |





What's the best way to setup configuration variables in a script? Like base_directories, user, passwords for db connect, etc.? So that all functions have access to them. Is it better to set this file up and then pass the variables one by one?



I'm pretty sure this is not the "best way" but this is how I do it. I have a configuration file which is "required" by all the other scripts, and it'd contain things like:
You may want to keep this file outside your public directory in case of (unlikely though it may seem) some sort of server configuration mishap.PHP Code:# file system paths
define( 'PATH_ROOT', '/home/someuser/public_html' );
define( 'PATH_INC', PATH_ROOT.'/inc' );
# web paths
define( 'WEB_ROOT', '' );
define( 'WEB_IMG', WEB_ROOT.'/images' );
# database
define( 'DB_HOST', 'localhost' );
define( 'DB_USER', 'abc' );
define( 'DB_PASS', 'def' );
define( 'DB_NAME', 'mydb' );
# etc...





it will have to stay in the script directory since I'd like to distribute the script and edit it with a configuration script.





You could also have a configuration class, then you can start a new instance of in the files needing it
Mark
I typically have a config file built like this:
And then in every page I call the config file like this:PHP Code:if (!defined('VALID_ENTRY_POINT')) {
header('HTTP/1.0 404 Not Found');
exit();
}
$CFG = array();
$CFG['paths']['rootDir'] = $_SERVER['DOCUMENT_ROOT'];
$CFG['paths']['classDir'] = $CFG['paths']['rootDir'] . '/classes';
$CFG['http']['disallowProxyCache'] = TRUE;
$CFG['http']['gzipCompress'] = TRUE;
I put the configuration into an array because it makes everything easy to transport, and great to print_r when debugging.PHP Code:define('VALID_ENTRY_POINT', TRUE);
require_once('config.php');
Defining the VALID_ENTRY_POINT in each page that calls the config file ensures that casual browsing doesn't expose anything.
Very much simplified, but I think it demonstrates my method.
Bookmarks