JuanBonnett
JuanBonnett

Reputation: 786

Use constants to include files

I got something like this, but it doesn't work, seems like it's not working because of the servername is shown.

DEFINE("APP_FOLDER", "website");
DEFINE("MODULES_DIR", $_SERVER["SERVER_NAME"].APP_FOLDER."/modules");

include_once(MODULES_DIR."/class-ViewRender.php");

It shows an error: *Warning: include_once(localhost/website/modules/class-ViewRender.php): failed to open stream.*

What I also want is that I can have a file like this

myappfolder/pages/users.php -> the file class-ViewRender.php should be successfully included

myappfolder/pages/administration/administrativeusers.php -> Here the file class-ViewRender.php should be successfully included as well.

How can I achieve this including the same config.php in every php file?

Upvotes: 0

Views: 142

Answers (2)

Fawzan
Fawzan

Reputation: 4849

This is a one major problem beginners face in PHP, I was affected alot. Best way to over come the issue is to using the 'File system_path'

for eg.

$white_list = array('127.0.0.1', '127.0.0.0','::1');

defined('DS')? null:define('DS', DIRECTORY_SEPARATOR);

if(!in_array($_SERVER['REMOTE_ADDR'], $white_list)){
    // Remote SERVER
    define('SITE_ROOT',       DS.'home'.DS.'some_name'.DS.'public_html'.DS.'your_web_root_folder_name');
}
else{
    //localhost
    define('SITE_ROOT', 'c:'.DS.'wamp'.DS.'www'.DS.'your_web_root_folder_name');
}

Then you can simply use SERVER_ROOT constant it in your PHP files.

Upvotes: 1

JuanBonnett
JuanBonnett

Reputation: 786

OK I think I solved it.

The trick is to have a config.php file inside the main folder, I mean, the root of the web application.

Then you can there declare Constants like CLASSES_FOLDER, "/modules/classes"

Then, doesn't matter the depth of the requested PHP script as long as you have the next line:

//Superdeep.php
include_once("../../../../../config.php");

you will be able to use whatever is inside config.php.

Is there a way to avoid having to guess all the "../" you have to put to get it working? I don't know yet...

Upvotes: 0

Related Questions