简体   繁体   English

在 PHP 中包含 header 和函数文件的正确方法

[英]Proper way to include header and functions files in PHP

I have my all files in public_html directory like this我的所有文件都在 public_html 目录中,如下所示

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

Now all is working fine in order/index.php in which I am including header like现在一切都在 order/index.php 中正常工作,其中我包括 header

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

Now I have tried include header in my order/info/index.php like below现在我尝试在我的订单/信息/索引中包含 header。php 如下所示

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

Header getting included properly in this too, but its giving me error called Header 也被正确包含在其中,但它给了我一个名为

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

I will have many similar errors because of directory structures.由于目录结构,我会遇到很多类似的错误。 I think I am not following proper way to include files so I can call it properly from any directory, sub directories without any issues.我认为我没有遵循正确的方法来包含文件,因此我可以从任何目录、子目录中正确调用它而不会出现任何问题。 Let me know if anyone here can help me for it.让我知道这里是否有人可以帮助我。

Thanks a lot!非常感谢!

You can define and retrieve the root of your project in several ways, then you can always access php files from this root.您可以通过多种方式定义和检索项目的根目录,然后您始终可以从该根目录访问 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/...';

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

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