【问题标题】:require_once Inside require_once Creates Path Issuerequire_once 内部 require_once 创建路径问题
【发布时间】:2012-12-22 16:20:32
【问题描述】:

我有这种情况:

  • 一个文件:/public_html/folderX/test.php 有一行:require_once '../functions/sendemail.php'
  • 另一方面,/public_html/functions/sendemail.php 有一行:require_once '../config.php'

config.php 在这种情况下完美加载。

当我尝试在不在文件夹 X 中的文件上添加 functions/sendemail.php 时出现问题,例如:

当我尝试在 public_html/test.php 上添加 require_once 'functions/sendemail.php' 时,我收到了以下错误消息:

警告:require_once(../config-min.php) [function.require-once]:打开流失败:public_html/test.php 中没有这样的文件或目录

如何使require_once '../config.php' 在functions/sendemail.php 中“独立”工作,因此无论它包含在任何文件中,都不会再出现“require_once”问题。

我尝试改成 'include_once' 但还是不行。

谢谢!

【问题讨论】:

    标签: php


    【解决方案1】:

    尝试类似的东西

    require_once( dirname(__FILE__).'/../config.php')
    

    【讨论】:

      【解决方案2】:

      尝试使用__DIR__ 获取脚本的当前路径。

      require_once(__DIR__.'../config.php');
      

      __DIR__ 仅适用于 php 5.3

       __DIR__ 
      
      The directory of the file. If used inside an include, the directory of 
      the included file is returned. This is equivalent to dirname(__FILE__). 
      This directory name does not have a trailing slash unless it is the root directory. 
      (Added in PHP 5.3.0.)
      

      【讨论】:

        【解决方案3】:

        我相信相对路径名在这里咬你。相对路径(据我所知)基于当前活动脚本的目录。当 includingrequiring 文件时,PHP 不会将 chdir 放入文件夹。最好的建议(以我有限的经验)是尽可能使用绝对路径。所以像:

        require_once('../config.php');
        

        会变成:

        require_once('/home/myuser/config.php'); // Or wherever the file really is
        

        dirname 函数可以在这种情况下提供帮助。

        【讨论】:

          【解决方案4】:

          您必须了解 PHP 会将目录更改为 outermost 脚本的目录。当您使用相对路径时(例如以./../ 或不以/ 开头的路径),PHP 将使用当前目录来解析相对路径。当您在代码中复制粘贴包含行时,这会导致问题。考虑这个目录结构:

          /index.php
          /admin/index.php
          /lib/include.php
          

          假设两个索引文件包含这些行:

          include_once("lib/include.php");
          

          当调用/index.php 时,上述行将起作用,但在调用/admin/index.php 时不起作用。

          解决方案是不要复制粘贴代码,在包含调用中使用正确的相对文件路径:

          /index.php       -> include_once("lib/include.php");
          /admin/index.php -> include_once("../lib/include.php");
          

          【讨论】:

            猜你喜欢
            • 2013-11-18
            • 2011-03-16
            • 2012-03-17
            • 2017-12-10
            • 1970-01-01
            • 2011-04-03
            • 2013-03-23
            • 2015-06-08
            • 2013-07-14
            相关资源
            最近更新 更多