![](/img/trans.png)
[英]how to include a file in php and still respect the relative links from that included file
[英]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的正确路径。
动物/canine.php
include('header.php);
变成
<a href="images/dog.jpg">
这不起作用,因为动物/图像/dog.jpg不存在。
因此,我的问题是,在包含header.php的header.php文件中,该文件将如何修改dog.jpg的URL以使其在index.php和animal / canine.php中都可以使用?
将include更改为使用绝对路径:
<a href="/images/dog.jpg">
这样,它们将基于您网站的根目录,并始终指向正确的文件夹。
创建一个名为$root_path
的新变量,并将相对于您所在页面的Web目录根目录的路径放入其中。 在包含header.php之前,请确保已声明它
这是mysite.com/junk/index.php
因此您的图片资源位于../images/
<?php
$root_path = '../'
include('header.php');
输出资产网址时,请在其前面放置$root_path
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.