2013-02-04 77 views
1

我想找到一個文件是否存在於服務器的public_html文件夾中。file_exists - PHP返回動態public_html路徑

第一次嘗試:

if (file_exists('./local-config.php')) { 

,但是這隻能當PHP文件調用上面的if語句是在同一文件夾......不會......

第二個嘗試

if (file_exists($_SERVER['SERVER_NAME'].'/local-config.php')) { 

不工作...

第三嘗試

if (file_exists('http://'. $_SERVER['SERVER_NAME'].'/local-config.php')) { 

也不起作用......

第四嘗試

$_SERVER['DOCUMENT_ROOT'] seems to fall short of my public_html folder! 

任何想法?

我可以得到這個工作,如果我把完整的路徑...例如

if (file_exists('/home/username/public_html/local-config.php')) { 

然而,這是沒有好到我,因爲腳本可以在多臺服務器上使用,所以我需要的東西一般。

是否有可能讓PHP動態返回public_html路徑?

+0

你只需添加斜線/像「/local-config.php」 – GGio

+0

我還沒有試過,因爲試過它會在根目錄中尋找名爲local-config.php的文件...例如與主目錄相同的目錄。 – Gravy

+0

不是真的取決於你的虛擬主機是如何設置的,對我來說,它看起來在public_html – GGio

回答

1

爲此,我在我的應用程序中創建了一個全局變量。類似:

define('ROOT', dirname(__FILE__)); 

然後我用這與像的文件名:

ROOT . '/my_file.php' 
+0

完美,謝謝!如果我在public_html文件夾的根目錄下運行,那麼我包含的任何文件也將能夠使用這個全局變量! :) – Gravy

0

嘗試做這樣的事情:

$path = dirname(__FILE__); 
// or just __DIR__ - it should be the same thing 

這將返回被呼叫的文件的完整路徑。在PHP中,__FILE__是「magic constant」。從幫助頁面:

The full path and filename of the file. If used inside an include, the name of 
the included file is returned. Since PHP 4.0.2, __FILE__ always contains an 
absolute path with symlinks resolved whereas in older versions it contained 
relative path under some circumstances. 

利用收集到的路徑,你應該能夠找出如何得到你想要的東西。