Skip to content
Advertisement

Proper way to include header and functions files in PHP

I have my all files in public_html directory like this

global_assets
assets/layouts/header.php
assets/setup/env.php
order/index.php
order/info/index.php

Now all is working fine in order/index.php in which I am including header like

include '../assets/layouts/header.php';

Now I have tried include header in my order/info/index.php like below

include '../../assets/layouts/header.php';

Header getting included properly in this too, but its giving me error called

PHP Fatal error:  require(): Failed opening required '../assets/setup/env.php' in /home/myusername/public_html/assets/layouts/header.php on line 7

I will have many similar errors because of directory structures. I think I am not following proper way to include files so I can call it properly from any directory, sub directories without any issues. Let me know if anyone here can help me for it.

Thanks a lot!

Advertisement

Answer

You can define and retrieve the root of your project in several ways, then you can always access php files from this root.

  1. environment variable

    include getenv('MY_PROJ_ROOT').'/assets/...';
    
  2. auto-prepend-file

    //php.ini
    auto_prepend_file="/path/to/prepend-file.php"
    
    //prepend-file.php
    define('MY_PROJ_ROOT', '/path/to/project-root');
    
    //any other files
    include MY_PROJ_ROOT.'/assets/...';
    
  3. include-path

    //php.ini
    include-path=".:/path/to/project-root"
    
    //other files
    include 'assets/...';
    
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement