Gamemorize Gamemorize - 8 days ago 4x
PHP Question

How to use a root path with require?

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

Then some subfolders eg

There is a shared functions.php alongside the login.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?


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';


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


Then you can simply use

require_once 'privatePath/secretFolder/functions.php';