如何使include()文件中的链接与不同的PHP文档相关


How to make links from include() file relative to different PHP documents?

我正在设置我的网站,以便使用include()语句来标准化页眉、页脚和导航等内容,例如

include('header.php);

然而,当我对两个不同目录中的页面使用相同的头文件时,header.php中包含的相对链接会中断,例如:

header.php
<a href="images/dog.jpg">

index.php
include('header.php);
成为
<a href="images/dog.jpg">

这样做是因为这是从index.php文件到dog.jpg的正确路径。

动物/犬.php
include('header.php);
成为
<a href="images/dog.jpg">

这不起作用,因为animals/images/dog.jpg不存在。

所以,我的问题是,当包含header.php时,我可以在header.php文件中更改什么,以将url调整为dog.jpg,从而在index.php和animals/canine.php中工作?

将includes更改为使用绝对路径:

<a href="/images/dog.jpg">

这样,它们将基于您网站的根目录,并始终指向正确的文件夹。

创建一个名为$root_path的新变量,并将web目录相对于所处页面的根路径放入其中。在包含header.php 之前,请确保已声明

这是mysite.com/junk/index.php,所以您的图像资产在../images/

<?php
$root_path = '../'
include('header.php');

输出资产URL时,请将$root_path放在其前面。