【问题标题】:How to INCLUDE php files in nested folders如何在嵌套文件夹中包含 php 文件
【发布时间】:2021-01-30 01:09:32
【问题描述】:

我是 php 新手并面临最初的问题:)。

我的目录结构如下:

site
   index
      homepagesections.php
   assets
       css
         style.css
   config
      db.php
   include
      header.php

index.php

在根文件夹中的 index.php 中,我需要包含 header.php 文件,其中包括 config/db.php 和 assets/css/style.css。

我已经尝试了所有选项(包括。DIR 选项)但失败了。包含这些文件以及 style.css 路径的最佳方式是什么?

【问题讨论】:

  • 请出示您遇到问题的代码。
  • 如果我无法找到答案,当然可以。

标签: php file directory include


【解决方案1】:

在 index.php 中:

include (__DIR__.'/include/header.php');

在 header.php 中:

include (__DIR__.'/../config/db.php');
include (__DIR__.'/../assets/css/style.css');

【讨论】:

  • 谢谢。我也可以对 style.css 使用 include 命令吗?
  • @Kumar 基本上是的,你可以像<style><?php include (__DIR__.'/../assets/css/style.css'); ?></style> 那样内联它。这是否是一个好的做法是一个讨论的问题。
  • 问题仍未解决:(。我会尽快发布完整的代码以便更好地沟通。谢谢。
【解决方案2】:

在 index.php 中,header 的路径是 include/header.php:

include('include/header.php');

在标题中,您的 db.php 路径是 ../config/db.php,因此您将拥有:

include('../config/db.php');

注意 '../' - 这是您从文件所在的目录向上导航 1 级的方式。在标题中添加 css 将类似于:

<link rel="stylesheet" href="../assets/css/style.css">

【讨论】:

  • 感谢您的回复。我也在做同样的事情,但失败了。所以我尝试了 DIR 功能,但也失败了。你能解释一下“包含”命令到底在做什么吗?我的意思是,如果“包含”命令类似于 cut n paste 那么当我在 index.php 中包含一个 php 文件时,该代码会粘贴在 index.php 中吗?如果包含的文件还包含一个文件,那么该文件代码也会粘贴在 index.php 中吗?如果是这样,那么我必须使用 index.php 文件位置的路径。请多多指教。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-04
  • 1970-01-01
  • 2011-10-09
  • 1970-01-01
相关资源
最近更新 更多