EnglishAdam
EnglishAdam

Reputation: 1390

How to use a root path with require?

I have a private section within a site with a folder structure like so

www.site.com/privatePath/secretFolder/login.php

Then some subfolders eg

www.site.com/privatePath/secretFolder/grandmasRecipes/applePie.php

There is a shared functions.php alongside the login.php

www.site.com/privatePath/secretFolder/functions.php (creates $connection, mysql blah blah)

I have various subfolders and files i wish to connect to functions.php, some created dynamically so the solution should work from any file/folder position whatsoever.

Just to clarify:

Because the same file could be called within different folders I would like it to call the functions.php file not from where the file is but in relation to the root folder. So without relative ../ etc references

my question: How can i access a required php file from any file within my website?

Upvotes: 3

Views: 2306

Answers (2)

EnglishAdam
EnglishAdam

Reputation: 1390

Alternative solution:

require ( $_SERVER['DOCUMENT_ROOT'] . "/privatePath/secretFolder/functions.php");

Will access functions.php file from any page in site.

Upvotes: 0

Phil
Phil

Reputation: 165069

My advice is never rely on any external path configuration (such as DOCUMENT_ROOT). Instead, use paths relative to the current script...

From login.php

require_once __DIR__ . '/functions.php';

From grandmasRecipes/applePie.php

require_once __DIR__ . '/../functions.php';

See http://php.net/manual/language.constants.predefined.php#constant.dir


An alternative might be to set the include_path for the current environment. You can do this in say a .user.ini file in your document root

; /home/cpanelLogIn/public_html/.user.ini

include_path="/home/cpanelLogIn/public_html/:."

Then you can simply use

require_once 'privatePath/secretFolder/functions.php';

anywhere

Upvotes: 4

Related Questions