Search code examples
phpdirectoryincludefilepath

How can I build a dynamic absolute path in PHP?


I've a web site made of some folders, one for each section (info, news, blog etc...). In each of these folders there is an index.php file that should load a layout (common to all). These are stored in a different folder in the root where there is also the main index.php file (the homepage). So i have something like this:

root
-index.php (home)
-/layout
--layout files
-/info
--index.php`

The index file in the /info folder should include the page layout from /layout. The problem is that the layout files should include other files from other folders. In layout files I put this:

include 'contents/page-element.php';

But if I try to reach the same page-element.php file from the index.php file in the /info folder, I should do:

include '../contents/page-element.php';

to go to the root and then reach the /layout folder.

I don't want to create a copy of the layout for the folders so I've tried $_SERVER['DOCUMENT_ROOT'], but it does not work in some cases on the localhost and even on the web server.

Can someone help me or let me know how I can build a dynamic absolute path?


Solution

  • By using the built-in constant __DIR__ you can get your absolute path

    by print it or save

    echo __DIR__;
    

    it will print something like this for you

    C:\Users\user\Desktop\test
    

    and there is also another constant that will get the absolute path for your file that executes the command __FILE__

    echo __FILE__;
    

    will give you a result like this

    C:\Users\user\Desktop\test\index.php