问题描述
我不敢相信PHP对此简单问题没有简单的解决方案. ASP.NET带有〜符号,可解决此问题,并从根级别开始执行所有操作.这是我的问题:
I can't believe PHP doesn't have an easy solution of this simple matter. ASP.NET has a ~ sign that cares of this issue and starts everything from root level. Here's my problem:
localhost/MySite
-->Admin
-- Edit.php
-->Class
-- class.EditInfo.php
-->Texts
-- MyInfo.txt
--ShowInfo.php
内部class.EditInfo.php我正在访问MyInfo.txt,所以我定义了一个相对路径"../Texts/MyInfo.txt".然后,我在Admin/Edit.php中创建了一个EditInfo对象,并访问了Texts/MyInfo.txt,它工作正常.
Inside class.EditInfo.php I am accessing MyInfo.txt so I defined a relative path "../Texts/MyInfo.txt". Then I created an object of EditInfo in Admin/Edit.php and accessed Texts/MyInfo.txt it worked fine.
但是现在我必须在ShowInfo.php中创建一个EditInfo对象并访问Texts/MyInfo.txt,这就是问题所在.每当我创建objEditInfo并尝试访问MyInfo.txt时都在类中使用相对路径时,出现文件不存在"错误.
But now I have to create an object of EditInfo in ShowInfo.php and access Texts/MyInfo.txt and here's the problem occurs. As I am using a relative path in my class whenever I am creating an objEditInfo and trying to access MyInfo.txt I am getting "File doesn't exist" error.
现在,我正在寻找与ASP.NET的〜/Texts/MyInfo.txt"等效的东西.有什么类似的东西吗???还是我必须设置一些if/else条件的路径?
Now I am looking for something that's equivalent to "~/Texts/MyInfo.txt" of ASP.NET. Is there anything similar to that out there??? Or do I have to set the path with some if/else condition?
更新:
我使用了$ _SERVER ['DOCUMENT_ROOT'].我使用的是我的实际网站所在的子文件夹.因此,我不得不使用$ _SERVER ['DOCUMENT_ROOT']."/mySite"&然后在其中添加其余地址("/Texts/MyInfo.php").
I used $_SERVER['DOCUMENT_ROOT']. I was using a subfolder where my actual website was. So I had to use $_SERVER['DOCUMENT_ROOT']."/mySite" & then adding rest of the address ("/Texts/MyInfo.php") to it.
推荐答案
使用ShowInfo.php
中的define
创建具有到根绝对路径的常量:
Create a constant with absolute path to the root by using define
in ShowInfo.php
:
define('ROOTPATH', __DIR__);
或者PHP< = 5.3
Or PHP <= 5.3
define('ROOTPATH', dirname(__FILE__));
现在使用它:
if (file_exists(ROOTPATH.'/Texts/MyInfo.txt')) {
// ...
}
或使用$_SERVER
中定义的DOCUMENT_ROOT
:
if (file_exists($_SERVER['DOCUMENT_ROOT'].'/Texts/MyInfo.txt')) {
// ...
}
这篇关于PHP根目录的绝对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!