繁体   English   中英

包含另一个文件的不同文件夹中的 PHP 包含文件

[英]Php include file in different folder that includes another file

我是 PHP 新手,我一直在尝试使文件 ( index.php ) 包含另一个文件 ( connect.php ),其中包含另一个文件 ( config.php ),但它们位于不同的文件夹中。

这是我的目录结构:

 > index.php (in the [root]...)
 > connect.php ([root]/admin/)
 > config.php ([root]/admin/)

这是我到目前为止:

索引.php

include './admin/connect.php'

连接.php

$directory = getcwd();
chdir(__DIR__);
include "config.php";
chdir($directory);

这实际上是有效的,但不知何故我不喜欢更改工作目录的想法。

有没有更好的方法来实现我的目标?

您可以将以下几行放在 index.php 的顶部,

索引.php

<?php

// Define native directory seperator. 
define('DS', DIRECTORY_SEPERATOR);

// Define absolute project root.
define('ROOT', getcwd().DS);

// Define absolute admin folder 
define('ADMIN_ROOT', ROOT.'admin'.DS);

include ADMIN_ROOT.'connect.php';

连接.php

<?php

include ADMIN_ROOT.'config.php';

使用include(); 根据某些输入,里面的字符串将导致不同的位置。

+ /var/www/
- index.php
  + /var/www/admin/
  - connect.php
  - config.php

您可以通过简单地提供包含文件名的字符串来引用同一文件夹中的内容。

// Include same-folder script
include('config.php');
// Include same-folder subfolder
include('admin/config.php');

您还可以从以正斜杠/开头的字符串引用文件绝对位置,这会将您带到根目录。

include('/var/www/admin/connect.php');

从文件夹中,您可以通过在字符串中使用..来上..文件夹。

// Here it is redundant because you are exiting a folder and re-entering it.
include('/var/www/admin/../admin/connect.php');

您还可以使用波浪号~引用您的用户主目录(无论哪个用户正在运行您的服务器软件)。

include('~/admin/connect.php');

使用简单的引用包含所需的文件对您来说非常简单。

/index.php

<?php
  // Here you need to go up a folder to reach the connect script.
  include('admin/connect.php');
?>

/admin/connect.php

<?php
  // Here config is in the same folder as connect, so it can be referenced as such.
  include('config.php');
?>

暂无
暂无

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

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