priti narang
priti narang

Reputation: 236

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?

Upvotes: 1

Views: 743

Answers (2)

vinod
vinod

Reputation: 2880

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;
}

Upvotes: 1

Vikas Umrao
Vikas Umrao

Reputation: 2615

You can call the files using relative path like this for

=>public_html=>first_dir=>index.php => include("../config.php");

=>public_html=>first_dir=>second_dir=>index.php => include("../../config.php");

=>public_html=>first_dir=>second_dir=>thired_dir=>index.php => include("../../../config.php");

OR You can also call in all the files like this

include $_SERVER['DOCUMENT_ROOT'] . '/config.php';

Upvotes: 1

Related Questions