Reputation: 11474
I'm new to PHP. I'm developing a new PHP website. My website folder structure is as below,
-SystemRoot
+Code
+Data_Access
-Public_HTML
+css
+js
+Templates
-resources
config.php
There I have a config file in resources directory, I need to include config.php
in most of other php pages in various directories. So I have to specify the path to config file differently in different pages like,
include_once '../resources/config.php';
include_once '../../resources/config.php';
Is there a way to overcome this & use a common (relative) path to config.php
that can be used in eny folder path within the project?
What is the common/best practice to include classes in php projects?
Upvotes: 1
Views: 2578
Reputation: 4592
You could route everything to your index.php
then define some constant's. Evrything routed to index.php will have access to these then.
define('SELF', pathinfo(__FILE__, PATHINFO_BASENAME));
define('RESOURCES', SELF . 'resources/');
Upvotes: 2
Reputation: 324840
Start your script with chdir($_SERVER['DOCUMENT_ROOT']);
. From there all your include
s and any other file functions such as file_exists
, fopen
and so on will work from the root directory of your website (usually public_html
).
Upvotes: 3
Reputation: 15042
I've done pretty much what you've done in the past, except that my require()
s are done differently:
require_once(str_replace('//','/',dirname(__FILE__).'/') .'../../config.php');
I then define other paths that can be used throughout like so:
// DIRECTORY_SEPARATOR is a PHP pre-defined constant
// (\ for Windows, / for Unix)
defined('DS') ? null : define('DS', DIRECTORY_SEPARATOR);
// Define Views URL path
defined('VIEW_URL') ? null : define('VIEW_URL', '/application/views');
// Define CSS URL path
defined('CSS_URL') ? null : define('CSS_URL', '/public/css');
// Define JavaScripts URL path
defined('JS_URL') ? null : define('JS_URL', '/public/js');
// Define site root
defined('SITE_ROOT') ? null :
define('SITE_ROOT', str_replace('//','/',dirname(__FILE__)));
// Define App path as 'application' directory
defined('APP_PATH') ? null : define('APP_PATH', SITE_ROOT.DS.'application');
// Define Includes path as 'application/includes' directory
defined('INC_PATH') ? null : define('INC_PATH', APP_PATH.DS.'includes');
// Define Helpers path as 'application/helpers' directory
defined('HELP_PATH') ? null : define('HELP_PATH', APP_PATH.DS.'helpers');
// Define Controllers path as 'includes/classes' directory
defined('CTLR_PATH') ? null : define('CTLR_PATH', APP_PATH.DS.'controllers');
// Define Models path as 'includes/classes' directory
defined('MOD_PATH') ? null : define('MOD_PATH', APP_PATH.DS.'models');
// Define Views path as 'includes/classes' directory
defined('VIEW_PATH') ? null : define('VIEW_PATH', APP_PATH.DS.'views');
Upvotes: 4
Reputation: 1886
If using php 5.x check out http://php.net/manual/en/language.oop5.autoload.php
Upvotes: 0