【发布时间】:2018-05-27 20:52:23
【问题描述】:
通常我们使用以下代码将php文件包含在彼此内部:
<?php
include_once 'include/config.php';
// OR
include 'include/config.php';
// OR
include_once $_SERVER['DOCUMENT_ROOT'].'include/config.php';
// ect...
?>
但上述代码仅适用于 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...
?>
我的意思是,当我们将 php 文件移动到子文件夹时,include_once 想要查看子文件夹名称,例如 (include_once 'subfolder/include/config.php';)。这是一个具有挑战性的情况,因为我们需要对许多文件中包含的页面执行此操作。
例如,我包含来自index.php 的include_once $_SERVER['DOCUMENT_ROOT'].'/functions/includes.php';,还包含来自所有php 文件(如header.php, posts.php, and ajax_post.php)的includes.php 文件。它在根文件夹中工作正常,但如果我们移动子文件夹中的文件,则 include.php 文件不包括没有子文件夹名称的文件。
也许使用.htaccess 也可以做到这一点。
我已经制作了这个 htaccess 代码,也许你有一个使用 htaccess 的解决方案。我必须说我曾尝试使用RewriteBase /subfoldername/,但包含文件不起作用。
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]
。 我的责任是,我们如何才能包含没有子文件夹名称的 php 文件?
【问题讨论】:
-
一种方法是使用set_include_path 配置这些路径。
-
为什么不使用相对路径
-
@cteski 嗯,它看起来是一个不错的解决方案。我要测试一下。
-
我通常使用 DIRECTORY_SEPARATOR 常量相对于文档根目录。使其在操作环境之间变得干净且可移植。
include_once($_SERVER['DOCUMENT_ROOT'].DIRECTORY_SEPARATOR."include_folder".DIRECTORY_SEPARATOR."included_file.php"); -
@Typel
include_folder是什么,我在问我的职责是,我们如何才能包含没有子文件夹名称的 php 文件 但你的答案有子文件夹名称??