在Windows和Linux上获取绝对URL路径

我包含一个名为includes / db.php的文件,而这个文件又需要connection_details.php </ p>

我遇到的问题是我必须使用以下行读取db.php的内容。</ p>

  $ dbSettingsFile = realpath(dirname(__ FILE__))。  “\ connection-details.txt”; 
$ lines = file($ dbSettingsFile); //文件输入数组
</ code> </ pre>

但如果我轮流 已经包含了一个类似。
/ subfolder / file.php </ p>

的文件中的db.php文件,其中包含行</ p>

  require('../ includes / db.php'); 
</ code> </ pre>

但是这将始终适用于Windows但我是正确的说,因为反向斜杠 在$ dbSettingsFile变量中,它在linux中不起作用?
我必须非常具体,因为如果你删除了realpath并运行了file.php它就不会选择正确的路径。</ p>
</ div >

展开原文

原文

I am including a file called includes/db.php which in turn requires connection_details.php

The issue I am having is I must read the content of db.php with this following line.

$dbSettingsFile = realpath( dirname( __FILE__ ) )."\connection-details.txt";
$lines = file($dbSettingsFile);//file in to an array

But if I am in turn already including the db.php file from a file that is something like. /subfolder/file.php

with the line

require('../includes/db.php');

But this will always work on windows but am I right in saying because of the backward slash in the $dbSettingsFile variable it will not work in linux? I have to be very specific like this because if you removed the realpath and ran file.php it would not pick up the correct path.

duanmianzhou5353
duanmianzhou5353 PHP_EOL?你的意思是DIRECTORY_SEPARATOR?
接近 7 年之前 回复
duanchongchu5177
duanchongchu5177 如果有疑问,请使用PHP_EOL常量(或只是正常的斜杠/)。Windows将接受这两者。
接近 7 年之前 回复

1个回答



您应该始终使用绝对文件名,因为您无法确定搜索相对路径的基本目录。</ p >

使用</ p>

require(__DIR __。'/。/ include / db.php'); </ code> </ p>

可以肯定。 </ p>

斜杠字符'/'将在Windows和Linux中用作目录分隔符。
小心 - 在Windows文件名中'db.php'和'DB.php'是相同的文件但是 不在Linux中。</ p>
</ div>

展开原文

原文

You should always use absolute filename, because you can't be sure about base directory where search for relative path will start.

Use

require( __DIR__ . '/../includes/db.php' );

to be sure.

Slash character '/' will work as directory separator in both Windows and Linux. Be careful - in Windows filenames 'db.php' and 'DB.php' are the same file but not in Linux.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐