【问题标题】:Proper way to include header and functions files in PHP在 PHP 中包含头文件和函数文件的正确方法
【发布时间】:2022-01-01 06:37:04
【问题描述】:

我的所有文件都在这样的 public_html 目录中

global_assets
assets/layouts/header.php
assets/setup/env.php
order/index.php
order/info/index.php

现在一切都在 order/index.php 中正常工作,我在其中包含类似标题

include '../assets/layouts/header.php';

现在我已经尝试在我的 order/info/index.php 中包含标头,如下所示

include '../../assets/layouts/header.php';

标题也正确包含在其中,但它给了我一个错误

PHP Fatal error:  require(): Failed opening required '../assets/setup/env.php' in /home/myusername/public_html/assets/layouts/header.php on line 7

由于目录结构,我会遇到很多类似的错误。我认为我没有遵循正确的方法来包含文件,因此我可以从任何目录、子目录中正确调用它而不会出现任何问题。让我知道这里是否有人可以帮助我。

非常感谢!

【问题讨论】:

  • 在你的文件路径之前使用__DIR__魔法方法。一个很好的read在这里了解。
  • 当在我的 info/index.php 中按照您的要求使用 DIR 时,它的包含标头但对于 header.php 所需的 env.php 仍然存在相同的问题
  • @ÁlvaroGonzález __DIR__ 实际上的意思是“文件的目录”。主脚本为$_SERVER['PHP_SELF']$argv[0]
  • @shingo 谢谢指正。我设法写出与我的想法完全相反的东西...... ????

标签: php


【解决方案1】:

您可以通过多种方式定义和检索项目的根目录,然后您可以随时从该根目录访问 php 文件。

  1. environment variable

    include getenv('MY_PROJ_ROOT').'/assets/...';
    
  2. auto-prepend-file

    //php.ini
    auto_prepend_file="/path/to/prepend-file.php"
    
    //prepend-file.php
    define('MY_PROJ_ROOT', '/path/to/project-root');
    
    //any other files
    include MY_PROJ_ROOT.'/assets/...';
    
  3. include-path

    //php.ini
    include-path=".:/path/to/project-root"
    
    //other files
    include 'assets/...';
    

【讨论】:

  • 这已经解决了这个问题。非常感谢先生!
猜你喜欢
  • 2010-11-15
  • 1970-01-01
  • 2016-08-05
  • 1970-01-01
  • 2020-07-31
  • 2015-01-12
  • 1970-01-01
  • 2017-08-27
  • 1970-01-01
相关资源
最近更新 更多