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.
现在我想在所有index.php中包含config.php文件,这些文件位于具有不同深度级别的不同2目录中。我的config.php存在于根文件夹中。
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?
现在我必须在每个文件夹中放置config.php文件,或者必须根据目录深度更改包含路径。有没有解决方案,我在每个文件中使用一个函数自动查找目录深度并自动包含该文件?
2 个解决方案
#1
Use following function to get 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;
}
}
#2
You can call the files using relative path like this for
您可以使用相对路径调用文件
=>public_html=>first_dir=>index.php => include("../config.php");
=> 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 => index.php => include(“../../ config.php”);
=>public_html=>first_dir=>second_dir=>thired_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';
#1
Use following function to get 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;
}
}
#2
You can call the files using relative path like this for
您可以使用相对路径调用文件
=>public_html=>first_dir=>index.php => include("../config.php");
=> 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 => index.php => include(“../../ config.php”);
=>public_html=>first_dir=>second_dir=>thired_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';