Search code examples
phpinclude-path

Find file path and include it


I have a problem with including a file in all my directory having one or more level depth.

I have directory structure like

=>public_html=>first_dir=>index.php
=>public_html=>first_dir=>second_dir=>index.php
=>public_html=>first_dir=>second_dir=>thired_dir=>index.php

Now I want to include config.php file in all index.php those are in different-2 directories having different level of depth. And my config.php exist in root folder.

For now I have to place config.php file in each folder or have to change include path according to directory depth. Is there any solution that I use one function in each file that automatically find directory depth and include that file automatically?


Solution

  • Use the following function to get a path from directory depth

    function get_include_path($file_name)
    {
        $folder_depth = substr_count($_SERVER["PHP_SELF"] , "/");
        $directory_level = 1; //If file exist in folder after root use 2
        if($folder_depth == false)
        {
            $folder_depth = 1;
        }
        return str_repeat("../", $folder_depth - $directory_level).$file_name;
    }