简体   繁体   English

PHP 包含根目录中的所有文件(如 CMS)

[英]PHP to include all files from root directory (like a CMS)

I need to create subfolders with their own index.php files inside them for my pages.我需要在其中为我的页面创建带有自己的 index.php 文件的子文件夹。 When I include the header and footer files in the root directory, however, the site breaks because the header file is looking for all the CSS and JavaScript files in the current directory. When I include the header and footer files in the root directory, however, the site breaks because the header file is looking for all the CSS and JavaScript files in the current directory.

How can I fix this?我怎样才能解决这个问题?

You can use relative paths in the include, and .. to go up a directory.您可以在包含中使用相对路径,并将..到 go 上一个目录。

include('../functions.php');

This will include functions.php from the parent folder.这将包括父文件夹中的 functions.php。 If it were 2 folders deep, it would be ../../functions.php如果它是 2 个文件夹深,它将是../../functions.php

This is the most common way of including things in other folders, actually providing a relative yet direct path.这是在其他文件夹中包含内容的最常见方式,实际上提供了相对但直接的路径。 Using the parsers include_path can work but is not as portable.使用解析器 include_path 可以工作,但不是可移植的。

Just a quick comparison of the execution plan of both approaches:只是快速比较两种方法的执行计划:

Using include('../functions.php');使用include('../functions.php'); :

  • Check parent folder, open functions.php检查父文件夹,打开functions.php

    Using include_path, lets say only 3 paths in list, and include('functions.php');使用 include_path,假设列表中只有 3 个路径,并且include('functions.php');

  • Check current folder, file does not exist检查当前文件夹,文件不存在
  • Check first path in include_path, file does not exist检查 include_path 中的第一个路径,文件不存在
  • Check second path in include_path, file does not exist检查 include_path 中的第二个路径,文件不存在
  • Check third path in include_path, open functions.php检查include_path中的第三个路径,打开functions.php

    Then you have to hope that someone doesn't put a functions.php in one of those other included paths...然后你必须希望有人没有把functions.php放在其他包含的路径之一中......

  • For the server side, add the root to your include_path setting (or, if you don't intend to include from anywhere else, replace the include_path with the root), and you'll be able to refer to the files in it from anywhere.对于服务器端,将根添加到您的include_path设置(或者,如果您不打算从其他任何地方包含,请将include_path替换为根),您将能够从任何地方引用其中的文件.

    Client-side, you'd use the <base> tag to tell a browser where URLs start from (ie: where relative URLs end up pointing to).在客户端,您将使用<base>标记告诉浏览器 URL 从何处开始(即:相对 URL 最终指向的位置)。 You only really need this if you're linking the CSS and JS rather than including them, but that's the more common scenario.只有在链接 CSS 和 JS 而不是包含它们时,您才真正需要这个,但这是更常见的情况。 (You'd usually include PHP, and link CSS/JS.) (您通常会包括 PHP,并链接 CSS/JS。)

    声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

     
    粤ICP备18138465号  © 2020-2024 STACKOOM.COM