为什么包含路径仅在开头没有“/”的情况下起作用


Why Include path works only without "/" in start?

我希望index.php包含一个位于include文件夹中的footer.html文件,该文件位于我的index.php所在的同一文件夹中。

我注意到如果我使用:

<?php include '/include/footer.html'; >

我会得到:

警告:包括(/include/footer.html):无法打开流:没有这样的 文件或目录

它只有在我使用时才会起作用:

<?php include 'include/footer.html'; >

这很令人困惑,因为同时,我确实使用第一种形式来包含脚本和图像:

<script src="/js/script.js"></script>

<img src="/images/logo.jpg">

顺便说一句,将所有包含的文件集中在指定的文件夹中是否更好?

令人困惑的是,PHP 的include()根据文件在服务器上的物理文件路径来查找文件。它与您的网址无关。

你可以做:

<?php include './include/footer.html'; >

或:

<?php include 'include/footer.html'; >

或:

<?php include __DIR__ . '/include/footer.html'; >

如果<?php echo __DIR__ . '/include/footer.html'; ?> ,您将在磁盘上看到 footer.html 的完整路径。在 Linux/UNIX 系统上,/ 是系统的根目录,因此当您使用 /include/footer.html 时,它会在系统的根目录中查找一个名为 include 的目录,并在其中查找一个footer.html