php - 多个包含多个目录错误

时间:2011-09-11 06:15:13

标签: php

这是我的目录列表:

>htdocs
-->MyWeb
---->admin
------>cms.php
---->images
---->controller
------>post.php
------>general.php
---->model
------>posts.php
------>sessions.php
------>connections.php
---->index.php

以下是从顶部开始的每个页面的包含:

cms.php:
    require_once('../model/sessions.php');
    require_once('../controller/post.php');
post.php:
    require_once('general.php');
    require_once('../model/posts.php');
general.php : none 
posts.php:
    require_once('sessions.php');
    require_once('connections.php');
sessions.php:
    require_once('connections.php');
connections.php : none
index.php:
    require_once('controller/post.php');

条件:用cms.php测试一切正常,我可以使用控制器提供的表格访问所有函数,控制器从模型中获取数据。 现在,管理事情已经完成,时间到了index.php来显示数据,我把它放在index.php里面,当我打开它时,这里发生了什么:

我收到错误,告诉我“require_once()”函数无法找到指定的文件。我用cms.php做到了这一点,好吧。错误不是来自index.php,而是来自 其中包含的文件(post.php)。

让我们再看看index.php,它包含了控制器,post.php使用“require_once('controller / post.php');”,但是post控制器本身包括另一个文件, 这是帖子模型“require_once('../ model / posts.php')”。当index.php使用 top folder perspective (MyWeb)查看控制器所需的文件时,会出现问题,然后读取包含的文件 在post控制器中完全是“require_once('../ model / posts.php')”= = index.php的一个文件夹,文件夹模型,这意味着:

  

htdocs> model> posts.php当然不存在。我第一次真的很困惑,然后我为此创造了一些作弊:

1. I put a variable $check = true ; before the require_once('controller/post.php') ; in index.php
2. then for each page that requires another file, i put these :
    //for example, in sessions.php
    if(isset($check)) {
        //old link which is like this : require_once('connections.php') ; has become :
        require_once('model/connections.php') ;
        //so in index.php perspective, the file can be reached
    }
    else {
        //old links, only executed when this page was not viewed from index.php
        require_once('connections.php') ;
    }
3. it works now, cms.php read the includes from old links, while index.php will read the included from new links.

现在,即使它有效,但我的代码看起来很丑陋且不一致,如果在将来,我可能会添加更多文件,更多包含。 问题:有人有更好的解决方案吗?如何访问应用程序的工作目录,例如在linux中使用:〜/ controller / post.php或〜/ model / posts.php。所以地址一致。 不能使用getcwd(),我不想显示我的文件的绝对路径。有没有人可以给我更好的解决方案来指定我的情况下的目录?

注意:原谅我的英语

2 个答案:

答案 0 :(得分:1)

  

如何访问应用程序的工作目录,例如在linux中使用:〜/ controller / post.php或〜/ model / posts.php。

$_SERVER['DOCUMENT_ROOT']

答案 1 :(得分:0)

DOCUMENT_ROOT有效,但如果您需要能够在子目录中移动您的应用程序,则无效,例如

domain.com/apps/myapp
domain.com/apps/myapp/v1

在这种情况下,我最喜欢的方法是在每个脚本中调用的配置文件中定义根目录:

// in /index.php
define("BASEDIR", dirname(__FILE__));

然后,您可以在需要的任何地方使用BASEDIR常量替换应用程序的完整路径。

相关问题