'Create variable that contains working path for including files on both localhost and live server (PHP)

I am working on a project with a lot of includes and requires. I don't want to change this everytime I deploy from localhost to my live server.

So I thought to use $_SERVER['DOCUMENT_ROOT'], which worked fine until I checked my git which pushes directly to a backup folder on my live server. It is not in the root, but one level lower.

All the files in this backup folder that use include or require get their files from my server root (public_html/) not the current folder the project is in (public_html/backup/).

So this wouldn't work. After that I tried getcwd();, this fixed above situation but now I can't include files on my localhost.

So now I thought to make a check to see if the file is currently on my local pc or on my live server like this:

$checkpath = getcwd();
$localcheck = 'C:\\';
 
// Test if path contains C:\
if(strpos($checkpath, $localcheck) !== false){
    $absolute_path = $_SERVER['DOCUMENT_ROOT'];
} else{
    $absolute_path = getcwd();
}

My only problem is how can I include this for all files when including is my issue?

Maybe there is a better way to get a path that always works no matter if it is live or local?



Solution 1:[1]

You can use set_include_path($absolute_path); to change the directory include/require looks from. You would then technically only need to call this once in every PHP request. Beware that you need to provide the actual path to set_include_path. For example, you would need to provide "/home/username/directory" instead of "~/directory".

set_include_path documentation.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1