I'm new to PHP. I've been looking at the documentation and am having a problem. I have a multi-page PHP site I am working on. I was having a problem with relative paths (PHP Relative Path Issues) and was pointed to the following url(PHP include relative path). I want to use something similar to the following code snippet in the post:
if (is_production()) {
define('ROOT_PATH', '/some/production/path');
}
else {
define('ROOT_PATH', '/root');
}
include ROOT_PATH . '/connect.php';
On what page do I add the define statement (index.php?) and how can I reference the ROOT_PATH on every subsequent page that has an include statement?
I tried adding the define statement to the index.php page but calling the ROOT_PATH on any other page results in: Use of undefined constant ROOT_PATH
Index.php: define('ROOT_PATH', '/some/production/path');
some other page: include_once(ROOT_PATH."/Library/API/database.inc.php");
You have 2 possible (common) approaches:
Create files for each environment like production.inc.php
and development.inc.php
and include the one you need in your index.php
by using your is_production()
condition.
-- OR --
Create a single file that contains
if (is_production()) {
define('ROOT_PATH', '/some/production/path');
} else {
define('ROOT_PATH', '/root');
}
and then just include that single file to all your pages that need those constants.
I believe my issue was a SCOPING Issue. Although I went with @ parthmahida and @Spechal suggestion, there was still an issue. I ended up having to look at scoping to see it in the functions.
If you want to include a file that will contain your environment configuration information and constants, it will always have to be relative to the script calling it.
<?php
// config.php
function is_production(){ // do something to return boolean }
if (is_production()) {
define('ROOT_PATH', '/some/production/path');
}
else {
define('ROOT_PATH', '/root');
}
...
<?php
// index.php
include 'config.php';
include ROOT_PATH . 'some-file.php';
// do stuff
...
<?php
// some-page.php
include 'config.php';
include ROOT_PATH . 'other-file.php';
// do stuff