0

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!

Vidhi Sharma
  • 143
  • 6
  • using `__DIR__` magic method before your file path. a good [read](https://stackoverflow.com/questions/32537477/how-to-use-dir) here to understand. – danish-khan-I Jan 01 '22 at 06:40
  • when use _DIR_ as per you in my info/index.php, its include header but I have still same issue remain for env.php which is required by header.php – Vidhi Sharma Jan 01 '22 at 06:57
  • @ÁlvaroGonzález `__DIR__` actually means "The directory of the file". Main script is `$_SERVER['PHP_SELF']` or `$argv[0]` – shingo Jan 02 '22 at 07:46
  • @shingo Thank you for the correction. I managed to write the exact opposite of what I had in mind... – Álvaro González Jan 02 '22 at 14:22

1 Answers1

1

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/...';
    
shingo
  • 18,436
  • 5
  • 23
  • 42