PHP问题包括全局路径
作者:互联网
我一直在面对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中阅读了这么多线程,并遵循以下建议
>使用文件的基本目录将常量定义为DOCUMENT_ROOT. (就像在SO中这样说-> https://stackoverflow.com/a/22912261/1001242)
>还尝试了各种选项,例如DIR,basedir(FILE)等,
>通过set_include_path()方法将我的应用程序目录(/ phpPractices / myApp)添加到include_path(如PHP, How to set include path和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'
我的list.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__)
标签:absolute-path,php,include,global 来源: https://codeday.me/bug/20191009/1877853.html