PHP 的问题包括全局路径


Issue with PHP include with global path

我一直面临着PHP包含的问题。根据互联网上的读数,我一直在使用相对路径来灵活。

只要我直接在每个文件中引用一个路径,比如

require_once '../includes/connection.php';  // it works fine.

当我使用全局常量引用此路径时,问题开始

require_once getDocumentRoot() . '/includes/connection.php', 

正如它所说的以下错误。

Warning: require_once(/phpPractices/myApp/includes/connection.php): failed to open stream: No such file or directory in /Applications/XAMPP/xamppfiles/htdocs/phpPractices/myApp/dir1/list.php on line 19".

我一直在阅读SO中的许多线程,并遵循以下建议

  1. 将常量定义为与文件的基本控制器DOCUMENT_ROOT。(就像它在SO -> https://stackoverflow.com/a/22912261/1001242 中所说的那样(
  2. 还尝试了各种选项,如DIR,basedir(FILE(等,
  3. 通过 set_include_path(( 方法将我的应用程序目录 (/phpPractices/myApp( 添加到include_path中(如 PHP 中所述,如何设置包含路径和 http://php.net/manual/en/function.set-include-path.php(

我的函数getDocumentRoot((定义如下。

function getDocumentRoot()
{
    $loc_pos_2 = strpos($_SERVER['REQUEST_URI'], "/", 1);
    $baseDir = substr($_SERVER['REQUEST_URI'], 0, $loc_pos_2);
    $baseDir = $baseDir . "/myApp";
    return $baseDir;
}

注意:我可以看到该文件是物理存在的。但是,file_exists(( 方法返回 false,我不明白为什么。可能这是一个令人担忧的原因?

仅供参考,我的目录结构如下。

htdocs
  phpPractices
    myApp --> Web App Root
      includes
         connection.php
      inc
         header.php
         footer.php
         global.php -- contains getDocumentRoot() method and included in header.php
      index.php
      dir1 --> my module specific dir
         list.php --> which needs 'connection.php'

我的列表.php包含以下内容

<?php
include_once '../inc/header.php'; // it works fine as I do relative to the path
//require_once '../includes/connection.php'; //works fine
require_once getDocumentRoot() . '/includes/connection.php'; // FAILS! :(
?>

但无济于事!任何摆脱此问题的建议将不胜感激。

提前感谢!

溶液

感谢所有回复的人。我有一个新的解决方法,可以帮助我:)

1. For all the menu items with links: 
    I use my getDocumentRoot() method which provides me - 
     '/phpPractices/myApp/' --> which is relative to my Web App.
2. For all the include, require functions : 
    I defined a different constant as below & as per this link: 
        https://stackoverflow.com/a/1488293/1001242
    define('APP_BASE_PATH', $_SERVER['DOCUMENT_ROOT'] . '/myApp');
    which returns me the complete absolute path which works fine for file inclusion.

我一直在干涉这两个问题。对于文件包含,getDocumentRoot(( 的输出"/phpPractices/myApp"失败,因为它试图在根目录("/phpPractices/"(中找到名为"phpPractices"的目录,这是根本原因。因此,我将它们一分为二,现在工作正常。

谢谢大家。非常感谢。

更新 getDocumentRoot(( 函数以返回绝对路径

function getDocumentRoot()
{
    return dirname(__FILE__);
}

或根据您的需要使用dirname(__FILE__)