PHP 在根文件夹中包含来自不同子目录的文件

PHP include files from different subdirectories within the root folder

我的问题类似于PHP include file strategy needed。我有以下文件夹结构:

/root/pages.php 
/root/articles/pages.php
/root/includes/include_files.php 
/root/img/images.jpg

/root”和“/root/articles”目录中的所有页面都有一个“header.php " 和 "footer.php" 文件包含在其中,它们存储在 "/root/includes" 目录中。

页眉和页脚都包含存储在“root/img/”目录中的图像。

根据以下建议:

how it`s possible to include a file (include();) from the root folder to a files from different subfolders?

How to use a PHP includes across multiple directories/sub directories with relative paths

我尝试了 **dirname** 解决方案和 $_SERVER['DOCUMENT_ROOT] 解决方案,将页眉和页脚包含在存储在 root 目录和 文章子目录。

但是,当我尝试使用任一方法(在页眉和页脚文件中)link 图像时,我 运行 遇到了问题:

<img src=" <?php echo dirname(__FILE__). '/img/image.jpg';?>">

Chrome 无法显示图像并抛出以下错误:

locally: Not allowed to load local resource: file:///C:/root/img/image.jpg

on the server: GET http://host.com/home/public_html/root/img/image.jpg 500 (Internal Server Error)

我检查了 URL,它们似乎是正确的。在谷歌上搜索解决方案后,我发现 chrome 出于安全原因阻止显示包含其完整文件路径的文件。

我该如何解决这个问题?或者是否有其他方法可以将文件(包括图像)包含到存储在任何子目录中的文件中?

这可能对你有帮助

$url = $_SERVER['DOCUMENT_ROOT'].'/img/image.jpg';
<img src="<?=$url?>">

@sandeep 的回答部分正确。因为

$_SERVER['DOCUMENT_ROOT'];

将再次返回根目录的完全限定路径。

<img src=" <?php echo 'http://localhost/favicon.ico';?>"/>

将 return 返回图像,因为现在我没有根据您的问题给它本地路径,而是服务器的 url 我是 运行.

使用 ../img/image.jpg 包含在 /root/articles.

中的文件中

使用 img/image.jpg 包含在 /root 中的文件中

对于您包含的脚本,请尝试使用 set_include_path

设置 includes_path
set_include_path( $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR );

然后,要在您的页面中包含脚本,您可以使用:

include( 'script.php' );

对于图像,在路径前加上斜杠 / ~ 即:

<img src='/img/image1.jpg' />

使用根相对路径比使用目录相对路径更容易,因此在前导斜杠前表示文件夹位于根目录中。