Gamemorize Gamemorize - 1 month ago 7
PHP Question

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?

Answer

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

Comments