如何在不指定子文件夹路径的情况下包含php文件

时间:2021-12-26 00:11:15

Normally we use the following code to include php files inside each other:

通常我们使用以下代码将php文件包含在彼此内部:

<?php 

include_once 'include/config.php';
// OR
include 'include/config.php'; 
// OR 
include_once $_SERVER['DOCUMENT_ROOT'].'include/config.php';
// ect...
?>

But the above codes only apply if the php files are in the root file. I mean, if we move our files into a subfolder. We need to make a change to the code we included in the php files. For example like this:

但是上面的代码只适用于php文件在根文件中。我的意思是,如果我们把文件移动到子文件夹中。我们需要修改php文件中包含的代码。例如像这样:

<?php 
    include_once 'subfolder/include/config.php';
    // OR
    include 'subfolder/include/config.php'; 
    // OR 
    include_once $_SERVER['DOCUMENT_ROOT'].'/subfolder/include/config.php';
    // ect...
?>

What I'm saying is that when we move our php files into the subfolder, then include_once want to see subfolder name like (include_once 'subfolder/include/config.php';). This is a challenging situation because we need to do this for the included page in many files.

我要说的是,当我们将php文件移动到子文件夹中时,include_once希望看到子文件夹的名称(include_once 'subfolder/include/config.php';)。这是一个具有挑战性的情况,因为我们需要在许多文件中为包含的页面执行此操作。

For example i include the include_once $_SERVER['DOCUMENT_ROOT'].'/functions/includes.php'; from the index.php and also included this includes.php file from all php files like header.php, posts.php, and ajax_post.php . It is working fine from the root folder but if we move the files in the subfolder then include.php file not including without subfolder name.

例如,我包含include_once $_SERVER['DOCUMENT_ROOT'].'/function /includes.php';从索引中。还包括了php和php。php文件来自所有php文件,如header。php,职位。php和ajax_post。php。它在根文件夹中工作得很好,但是如果我们移动子文件夹中的文件,则包含。没有子文件夹名称的php文件。

Maybe it is also possible to do this with .htaccess.

也许使用.htaccess也可以实现这一点。

I have made this htaccess code maybe you have a solution with htaccess. I must be say i have tryed to use RewriteBase /subfoldername/ but include files didn't worked.

我做了这个htaccess代码也许你有一个htaccess的解决方案。我必须说我已经尝试使用RewriteBase /subfoldername/但是include文件没有工作。

Options +FollowSymLinks -MultiViews
RewriteEngine On 
RewriteBase /

RewriteCond %{REQUEST_METHOD} !POST
RewriteCond %{THE_REQUEST} \s/+(.+?)\.php[\s?] [NC]
RewriteRule ^ /%1 [R=302,NE,L]

RewriteCond %{REQUEST_METHOD} !POST
RewriteCond %{THE_REQUEST} /index\.php [NC]
RewriteRule ^(.*)index\.php$ /$1 [L,R=302,NC,NE]

RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]

RewriteRule ^group/([\w-]+)/?$ sources/group.php?group_username=$1 [L,QSA]  
RewriteRule ^profile/([\w-]+)/?$ sources/user_profile.php?username=$1 [L,QSA]
RewriteRule ^profile/(followers|friends|photos|videos|locations|musics)/([\w-]+)/?$ sources/$1.php?username=$2 [L,QSA]     

RewriteRule ^admin/(.*)$ admin/index.php?page=$1 [L,QSA]

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ $1.php [L]  

RewriteRule ^(.+?)/?$ index.php?pages=$1 [L,QSA]

. My responsibility is, how can we include php files without subfolder name?

。我的职责是,如何包含没有子文件夹名称的php文件?

10 个解决方案

#1


15  

You can use auto_prepend_file directive in your .htaccess to make a .php file included before all of your php files.

可以在.htaccess中使用auto_prepend_file指令创建一个包含在所有php文件之前的.php文件。

If you're using mod_php then have this line in your .htaccess:

如果你正在使用mod_php,那么在你的。htaccess中有这一行:

php_value auto_prepend_file "/Applications/MAMP/htdocs/script/env.php"

Note that for PHP-FPM you need to have these equivalent line in your .user.ini file:

请注意,对于PHP-FPM,您需要在.user中具有这些等效的行。ini文件:

auto_prepend_file = "/Applications/MAMP/htdocs/script/env.php"

Then create a new file env.php in your project base directory with just one line:

然后创建一个新文件env。php在您的项目基础目录中只有一行:

<?php
   $baseDir = __dir__ . '/';
?>

This line sets a variable $baseDir that has value of your project base directory i.e. /Applications/MAMP/htdocs/script/ OR /Applications/MAMP/htdocs/subdir/script/

这一行设置一个变量$baseDir,它具有项目基目录的值,即/Applications/MAMP/htdocs/script/ OR / application /MAMP/htdocs/subdir/script/

Then use this variable $baseDir anywhere you have to include other files such as:

然后使用这个变量$baseDir,您必须包含其他文件,例如:

include_once $baseDir.'functions/includes.php';

include_once $baseDir.'functions/get.php';

#2


6  

__DIR__ is certainly what you are looking for. Use it to provide relative paths for required files. I would highly suggest using require_once or include_once for all library files.

你当然是在找工作。使用它为所需的文件提供相对路径。我强烈建议对所有库文件使用require_once或include_once。

include_once dirname(dirname(__DIR__))."/include/config.php";

#3


6  

You have to use function set_include_path() and somewhere in your bootstrap.php or index.php add next code:

您必须使用函数set_include_path()和引导程序中的某个位置。php或索引。php添加下一个代码:

<?php
$path = '/usr/pathToYourDir';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);

now everywhere below you can write this:

下面的每一个地方都可以这样写:

include_once 'include/config.php';
// or
include_once 'include/db/index.php';
// etc

And in case you need to move your code into another directory - you have only to change value of path varibalbe $path = '/usr/pathToYourDir'; to new path to your directory.

如果您需要将代码移动到另一个目录—您只需更改path varibalbe $path = '/usr/pathToYourDir'的值;到目录的新路径。

#4


5  

Ok, I'm not a fan of doing this, but it will get the job done, as requested:

好吧,我不喜欢这样做,但它会按要求完成工作:

$newpath="";

$dirs = array_filter(glob('*'), 'is_dir');
foreach ($dirs as $location) {
    $newpath .= PATH_SEPARATOR . $location; 
}
set_include_path(get_include_path() . $newpath);

The above code will find all subfolders from where this file is running, and add them all to the current include path. by changing the glob from:

上面的代码将找到该文件运行的所有子文件夹,并将它们全部添加到当前包含路径中。将手套由:

glob('*') 

to

glob('includes/*')  or glob('includes' . DIRECTORY_SEPARATOR . '*')

You can restrict it to only subfolders under includes.

您可以将它限制在include下的子文件夹中。

The above is not tested, I just threw the code together, but it illustrates a way to do what you're asking for.

上面的代码没有经过测试,我只是将代码组合在一起,但是它说明了一种实现您所要求的功能的方法。

I would still recommend putting files in determined locations rather than trying to include them from anywhere.

我仍然建议将文件放在确定的位置,而不是尝试从任何地方包含它们。

#5


4  

This is how I would do it.

我就是这样做的。

//----- some global location like index.php

if(!defined("CONFIG_PATH")) define("PATH_CONFIG", __DIR__."/include/");

//------------ then later in some other file

if(!defined("CONFIG_PATH"))die("Config path is not defined.");

include_once CONFIG_PATH.'config.php';

Then when you change it you just update

当你改变它的时候,你只需要更新

if(!defined("CONFIG_PATH")) define("PATH_CONFIG", __DIR__."/include/subfolder/");

I would say this is the "Traditional" way to do it, and it's perfectly fine to use a global constant for this. It's not something you want changing at run time. You need access to it in many places, potentially. You can check if your files are accessed properly .. etc.

我认为这是一种“传统”的方法,使用一个全局常数是完全可以的。这不是您希望在运行时更改的内容。您可能需要在许多地方访问它。您可以检查您的文件是否被正确访问。等。

Many many many, MVC frameworks do it this exact way.

很多MVC框架都是这样做的。

#6


3  

Refer this link hope it helps http://www.geeksengine.com/article/php-include-path.html

参考这个链接希望它能帮助http://www.geeksengine.com/article/php-include-path.html

#7


2  

Here's an example of an approach that requires your files upfront via the auto_prepend_file directive.

这里有一个方法的例子,它需要通过auto_prepend_file指令预先提交文件。

bootstrap.php:

bootstrap.php:

<?php

$require_upfront = function($dir) {
    require_once $dir . '/one.php';
    require_once $dir . '/two.php';
};

$require_upfront(__DIR__ . '/inc');

Add to php config, here .htaccess example:

添加到php配置,这里。htaccess示例:

php_value auto_prepend_file "/abs/path/to/bootstrap.php"

#8


2  

If you have the file's name unique in all server, you can make a research of this using a research like this.

如果您在所有服务器中都有该文件的唯一名称,您可以使用这样的研究对其进行研究。

I think that this solution isn't better when this script run a lot of, but you can include if the include function fails, using try and catch (if you use this method watch the php version) or if you know that this path change once a day you can make a file which is launched with routine.

我认为这个解决方案并不好当这个脚本运行很多,但是你可以包括如果包括函数失败,使用try和catch(如果你使用这个方法看php版本)或者如果你知道这条路改变一天一次可以使文件与程序启动。

If you make this, you need to store this path, but I don't know if there is a method for make global variable. My solution is to store or in a DB or in a file.

如果你这样做,你需要存储这个路径,但是我不知道是否有一个方法可以让全局变量。我的解决方案是将其存储在DB或文件中。

I hope I have helped you.

我希望我帮助了你。

#9


1  

What I understand from the answer https://*.com/a/50632691/7362396 is that you need to include files based on the directory of the entrypoint script.

我从https://*.com/a/50632691/7362396中了解到的是,您需要根据entrypoint脚本的目录包含文件。

A solution for this without the need for Apache or php.ini auto_prepend_file could be to use getcwd(). It returns the current working directory, which should be the path of the entrypoint/main script, even when called in included files.

一个无需Apache或php的解决方案。ini auto_prepend_file可以使用getcwd()。它返回当前工作目录,该目录应该是entrypoint/main脚本的路径,即使在被包含的文件中调用时也是如此。

Can you try if simply using getcwd() instead of $baseDir works?:

你能不能试试用getcwd()代替$baseDir ?

include_once getcwd().'/functions/includes.php';

include_once getcwd().'/functions/get.php';

#10


0  

Using Apache to fix your app is solving it at the wrong level.

使用Apache修复应用程序是在错误的层次上解决它。

If you have to update a bunch of files in your code when the location of a file changes, that is your code telling you that you have made a bad architectural decision. So fix the actual problem and stop repeating yourself.

如果您必须在文件的位置更改时更新代码中的一堆文件,那就是您的代码告诉您已经做出了糟糕的体系结构决策。因此,解决实际问题,停止重复自己。

Define where your includes live in one place, and then when needed, update that one place accordingly.

定义包含在一个地方的位置,然后在需要时相应地更新该位置。

One way to do this is set a constant at the root of your app. This assumes you have a bit of code at the root of your app that is called on every page. This would likely be index.php or a script included by index.php:

一种方法是在你的应用程序的根上设置一个常数。这假设你在每个页面的根上都有一些代码。这很可能是指数。php或由index.php包含的脚本:

// index.php or a file included by index.php
const MY_INCLUDE_PATH = __DIR__ . '/path/to/subfolder`

Then your other scripts can call include using the constant:

然后您的其他脚本可以调用include使用常量:

// some other script included to handle the page
include MY_INCLUDE_PATH . '/config.php';
include MY_INCLUDE_PATH . '/some-other-include.php';

Although if they all want to include the config.php file, maybe just go ahead and include it in your index.php.

尽管他们都想包含配置。php文件,可以直接在index.php中包含它。

This is not a "bad" global you want to avoid. It is using constants as they are intended. Constants are part of the namespace, if you are using a namespace for your app.

这不是一个你想要避免的“坏”全球。它按照预期使用常数。常量是名称空间的一部分,如果您正在为应用程序使用名称空间。

This assumes there is one include subfolder that sometimes changes places and a script somewhere that is a part of every request. Is that correct? If not, please post your directory structure.

这假定有一个include子文件夹,它有时会更改位置,而某个脚本是每个请求的一部分。那是正确的吗?如果没有,请发布您的目录结构。

A function would also work, and could include logic based on things such as the path of the calling script:

一个函数也可以工作,它可以包含基于诸如调用脚本路径之类的逻辑:

// index.php or a file included by index.php
my_include_function($path) {
  //do stuff
}

The other scripts might call this function like so:

其他脚本可以这样调用这个函数:

// some other script included to handle the request
my_include_function(__FILE__);

Then when things change, you simply update one function in one file.

当事情发生变化时,只需在一个文件中更新一个函数。

This all assumes you have an index.php or similar script that handles every request and can be the single point of control for defining the function or constant. If that's not the case, it should be!

所有这些都假设你有一个索引。php或类似的脚本处理每个请求,可以作为定义函数或常量的单个控制点。如果不是这样,那应该是!

Updating your code to use a router (here is one) would take maybe 10 minutes and potentially simplify that gnarly .htaccess file you posted.

更新您的代码以使用路由器(这里是一个)可能需要10分钟,并可能简化您发布的gnly .htaccess文件。

#1


15  

You can use auto_prepend_file directive in your .htaccess to make a .php file included before all of your php files.

可以在.htaccess中使用auto_prepend_file指令创建一个包含在所有php文件之前的.php文件。

If you're using mod_php then have this line in your .htaccess:

如果你正在使用mod_php,那么在你的。htaccess中有这一行:

php_value auto_prepend_file "/Applications/MAMP/htdocs/script/env.php"

Note that for PHP-FPM you need to have these equivalent line in your .user.ini file:

请注意,对于PHP-FPM,您需要在.user中具有这些等效的行。ini文件:

auto_prepend_file = "/Applications/MAMP/htdocs/script/env.php"

Then create a new file env.php in your project base directory with just one line:

然后创建一个新文件env。php在您的项目基础目录中只有一行:

<?php
   $baseDir = __dir__ . '/';
?>

This line sets a variable $baseDir that has value of your project base directory i.e. /Applications/MAMP/htdocs/script/ OR /Applications/MAMP/htdocs/subdir/script/

这一行设置一个变量$baseDir,它具有项目基目录的值,即/Applications/MAMP/htdocs/script/ OR / application /MAMP/htdocs/subdir/script/

Then use this variable $baseDir anywhere you have to include other files such as:

然后使用这个变量$baseDir,您必须包含其他文件,例如:

include_once $baseDir.'functions/includes.php';

include_once $baseDir.'functions/get.php';

#2


6  

__DIR__ is certainly what you are looking for. Use it to provide relative paths for required files. I would highly suggest using require_once or include_once for all library files.

你当然是在找工作。使用它为所需的文件提供相对路径。我强烈建议对所有库文件使用require_once或include_once。

include_once dirname(dirname(__DIR__))."/include/config.php";

#3


6  

You have to use function set_include_path() and somewhere in your bootstrap.php or index.php add next code:

您必须使用函数set_include_path()和引导程序中的某个位置。php或索引。php添加下一个代码:

<?php
$path = '/usr/pathToYourDir';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);

now everywhere below you can write this:

下面的每一个地方都可以这样写:

include_once 'include/config.php';
// or
include_once 'include/db/index.php';
// etc

And in case you need to move your code into another directory - you have only to change value of path varibalbe $path = '/usr/pathToYourDir'; to new path to your directory.

如果您需要将代码移动到另一个目录—您只需更改path varibalbe $path = '/usr/pathToYourDir'的值;到目录的新路径。

#4


5  

Ok, I'm not a fan of doing this, but it will get the job done, as requested:

好吧,我不喜欢这样做,但它会按要求完成工作:

$newpath="";

$dirs = array_filter(glob('*'), 'is_dir');
foreach ($dirs as $location) {
    $newpath .= PATH_SEPARATOR . $location; 
}
set_include_path(get_include_path() . $newpath);

The above code will find all subfolders from where this file is running, and add them all to the current include path. by changing the glob from:

上面的代码将找到该文件运行的所有子文件夹,并将它们全部添加到当前包含路径中。将手套由:

glob('*') 

to

glob('includes/*')  or glob('includes' . DIRECTORY_SEPARATOR . '*')

You can restrict it to only subfolders under includes.

您可以将它限制在include下的子文件夹中。

The above is not tested, I just threw the code together, but it illustrates a way to do what you're asking for.

上面的代码没有经过测试,我只是将代码组合在一起,但是它说明了一种实现您所要求的功能的方法。

I would still recommend putting files in determined locations rather than trying to include them from anywhere.

我仍然建议将文件放在确定的位置,而不是尝试从任何地方包含它们。

#5


4  

This is how I would do it.

我就是这样做的。

//----- some global location like index.php

if(!defined("CONFIG_PATH")) define("PATH_CONFIG", __DIR__."/include/");

//------------ then later in some other file

if(!defined("CONFIG_PATH"))die("Config path is not defined.");

include_once CONFIG_PATH.'config.php';

Then when you change it you just update

当你改变它的时候,你只需要更新

if(!defined("CONFIG_PATH")) define("PATH_CONFIG", __DIR__."/include/subfolder/");

I would say this is the "Traditional" way to do it, and it's perfectly fine to use a global constant for this. It's not something you want changing at run time. You need access to it in many places, potentially. You can check if your files are accessed properly .. etc.

我认为这是一种“传统”的方法,使用一个全局常数是完全可以的。这不是您希望在运行时更改的内容。您可能需要在许多地方访问它。您可以检查您的文件是否被正确访问。等。

Many many many, MVC frameworks do it this exact way.

很多MVC框架都是这样做的。

#6


3  

Refer this link hope it helps http://www.geeksengine.com/article/php-include-path.html

参考这个链接希望它能帮助http://www.geeksengine.com/article/php-include-path.html

#7


2  

Here's an example of an approach that requires your files upfront via the auto_prepend_file directive.

这里有一个方法的例子,它需要通过auto_prepend_file指令预先提交文件。

bootstrap.php:

bootstrap.php:

<?php

$require_upfront = function($dir) {
    require_once $dir . '/one.php';
    require_once $dir . '/two.php';
};

$require_upfront(__DIR__ . '/inc');

Add to php config, here .htaccess example:

添加到php配置,这里。htaccess示例:

php_value auto_prepend_file "/abs/path/to/bootstrap.php"

#8


2  

If you have the file's name unique in all server, you can make a research of this using a research like this.

如果您在所有服务器中都有该文件的唯一名称,您可以使用这样的研究对其进行研究。

I think that this solution isn't better when this script run a lot of, but you can include if the include function fails, using try and catch (if you use this method watch the php version) or if you know that this path change once a day you can make a file which is launched with routine.

我认为这个解决方案并不好当这个脚本运行很多,但是你可以包括如果包括函数失败,使用try和catch(如果你使用这个方法看php版本)或者如果你知道这条路改变一天一次可以使文件与程序启动。

If you make this, you need to store this path, but I don't know if there is a method for make global variable. My solution is to store or in a DB or in a file.

如果你这样做,你需要存储这个路径,但是我不知道是否有一个方法可以让全局变量。我的解决方案是将其存储在DB或文件中。

I hope I have helped you.

我希望我帮助了你。

#9


1  

What I understand from the answer https://*.com/a/50632691/7362396 is that you need to include files based on the directory of the entrypoint script.

我从https://*.com/a/50632691/7362396中了解到的是,您需要根据entrypoint脚本的目录包含文件。

A solution for this without the need for Apache or php.ini auto_prepend_file could be to use getcwd(). It returns the current working directory, which should be the path of the entrypoint/main script, even when called in included files.

一个无需Apache或php的解决方案。ini auto_prepend_file可以使用getcwd()。它返回当前工作目录,该目录应该是entrypoint/main脚本的路径,即使在被包含的文件中调用时也是如此。

Can you try if simply using getcwd() instead of $baseDir works?:

你能不能试试用getcwd()代替$baseDir ?

include_once getcwd().'/functions/includes.php';

include_once getcwd().'/functions/get.php';

#10


0  

Using Apache to fix your app is solving it at the wrong level.

使用Apache修复应用程序是在错误的层次上解决它。

If you have to update a bunch of files in your code when the location of a file changes, that is your code telling you that you have made a bad architectural decision. So fix the actual problem and stop repeating yourself.

如果您必须在文件的位置更改时更新代码中的一堆文件,那就是您的代码告诉您已经做出了糟糕的体系结构决策。因此,解决实际问题,停止重复自己。

Define where your includes live in one place, and then when needed, update that one place accordingly.

定义包含在一个地方的位置,然后在需要时相应地更新该位置。

One way to do this is set a constant at the root of your app. This assumes you have a bit of code at the root of your app that is called on every page. This would likely be index.php or a script included by index.php:

一种方法是在你的应用程序的根上设置一个常数。这假设你在每个页面的根上都有一些代码。这很可能是指数。php或由index.php包含的脚本:

// index.php or a file included by index.php
const MY_INCLUDE_PATH = __DIR__ . '/path/to/subfolder`

Then your other scripts can call include using the constant:

然后您的其他脚本可以调用include使用常量:

// some other script included to handle the page
include MY_INCLUDE_PATH . '/config.php';
include MY_INCLUDE_PATH . '/some-other-include.php';

Although if they all want to include the config.php file, maybe just go ahead and include it in your index.php.

尽管他们都想包含配置。php文件,可以直接在index.php中包含它。

This is not a "bad" global you want to avoid. It is using constants as they are intended. Constants are part of the namespace, if you are using a namespace for your app.

这不是一个你想要避免的“坏”全球。它按照预期使用常数。常量是名称空间的一部分,如果您正在为应用程序使用名称空间。

This assumes there is one include subfolder that sometimes changes places and a script somewhere that is a part of every request. Is that correct? If not, please post your directory structure.

这假定有一个include子文件夹,它有时会更改位置,而某个脚本是每个请求的一部分。那是正确的吗?如果没有,请发布您的目录结构。

A function would also work, and could include logic based on things such as the path of the calling script:

一个函数也可以工作,它可以包含基于诸如调用脚本路径之类的逻辑:

// index.php or a file included by index.php
my_include_function($path) {
  //do stuff
}

The other scripts might call this function like so:

其他脚本可以这样调用这个函数:

// some other script included to handle the request
my_include_function(__FILE__);

Then when things change, you simply update one function in one file.

当事情发生变化时,只需在一个文件中更新一个函数。

This all assumes you have an index.php or similar script that handles every request and can be the single point of control for defining the function or constant. If that's not the case, it should be!

所有这些都假设你有一个索引。php或类似的脚本处理每个请求,可以作为定义函数或常量的单个控制点。如果不是这样,那应该是!

Updating your code to use a router (here is one) would take maybe 10 minutes and potentially simplify that gnarly .htaccess file you posted.

更新您的代码以使用路由器(这里是一个)可能需要10分钟,并可能简化您发布的gnly .htaccess文件。