Page 1 of 1

Cross-Server PHP Configuration Files Rate Topic: -----

#1 Dormilich  Icon User is online

  • 痛覚残留
  • member icon

Reputation: 3402
  • View blog
  • Posts: 9,614
  • Joined: 08-June 10

Posted 18 June 2010 - 12:43 AM


Cross-Server PHP Configuration Files

After a recent discussion, I felt it to be a good idea to share my insight when it comes to load a configuration or script file, that should work regardless from which subdirectory or webserver you call this file.

First there is the directory setup of the project. Since most internet servers are running some kind of unix/linux, I’ll stick to their file system.

Project Setup
/var/www/project           -- the project’s root directory
/var/www/project/config    -- the project’s configuration directory
/var/www/project/lib       -- class & function definitions go here
/var/www/project/includes  -- other include files (scripts, content files, template files, etc.)

Next thing, we create a script in the config directory, that determines the project’s root directory. By using the magic constant __FILE__, it doesn’t matter wich server we operate on, so this file is the same for all our test and live servers.

define("BASE_DIR", realpath(dirname(__FILE__) . '/..') . "/");
define("LIB_DIR", BASE_DIR . "lib/");
define("INC_DIR", BASE_DIR . "includes/");
define("CONFIG_DIR", BASE_DIR . "config/");

Now to the interesting part. Since we want to go easy on calling this directory script, we have to tell our server to look for relatively addressed files not only in the usual places (usually the current directory and the php installation directory), we have to modify the include_path setting in php.ini. On most live/dedicated servers, you are not allowed to alter php.ini yourself, thus we have to use Apache’s .htaccess file to do it (this relieves us from doing ini_set() on every page). The current value of include_path can be viewed in phpinfo() (core section).

Pay attention, this file is different for every server!

php_value include_path ".:/lib/php:/var/www/project/conf"

now you can include the directory script in every script/page.
    require "dir.php";
    // now you can use BASE_DIR and all the other constants to reference files

Note: it is recommended to use absolute paths when accessing files, because the PHP interpreter has to resolve the relative paths to absolute paths anyway.

Happy Coding,


This post has been edited by Dormilich: 24 June 2010 - 05:26 AM

Is This A Good Question/Topic? 6
  • +

Page 1 of 1