2011-09-07 43 views
1

我是PHP新手,所以這是一個非常簡單的問題。假設我有兩個文件夾:FolderA和FolderB。在FolderA中,我有一個PHP文件。在FolderB內,我有一個證書。如果我想在PHP文件中插入證書的相對路徑,這是否是這樣的路徑:../FolderB/Certificate.pem簡單的PHP路徑問題

感謝您的幫助!

回答

3

您的解決方案完全取決於FolderA中的文件是否位於「包含樹」的頂部。

一個更好的解決辦法是使用絕對路徑,例如

// FolderA/file.php 

// PHP 5.3 only 
$path = realpath(__DIR__ . '/../FolderB/Certificate.pem'); 

// or if stuck with PHP 5.2 or earlier 
$path = dirname(dirname(__FILE__)) . '/FolderB/Certificate.pem'; 

爲了說明爲什麼絕對路徑比較好,考慮這

// FolderA/file.php 
$path = '../FolderB/Certificate.pem'; 

// some-other-file-in-the-root-directory.php 
include 'FolderA/file.php'; 
// $path is now incorrect as it points to 
// ROOT . '../FolderB/Certificate.pem' 
+0

對不起,我的意思是相對路徑,但你的解決方案沒有第一個斜線。只是想檢查一下,以確保它在PHP中沒有不同。謝謝你的幫助!! –

+0

爲什麼絕對路徑在這個特定情況下更好? – sanmai

+1

@sanmai如果從其他地方包含'FolderA/file.php',路徑的相對性會發生變化。使用絕對路徑可確保正確性。 – Phil

0

真。

/* FolderA/test.php: */ 
var_dump(is_file('../FolderB/Certificate.pem'));