2009-10-16 174 views
0

如何輕鬆將路徑映射到文件?如何輕鬆地從不同文件夾位置映射文件路徑?

public_html/api/function.php 
<?php 

function writetologfile($content) 
{ 

    $filename = 'logfile/testing_randomstring.txt'; 

    if (!$handle = fopen($filename, 'a')) 
    { 
     echo "Cannot open file ($filename)"; 
     exit; 
    } 
    fclose($handle);  
} 

?> 

文本文件的實際路徑是public_html/r/admin/logfile/testing_randomstring.txt

,所以如果我在public_html/folder1/folder2/addlog.php運行該腳本,它將無法找到路徑testing_randomstring.txt

addlog.php 
<?php 

include("../../api/function.php"); 

writetologfile('hahaha'); 

?> 

我如何能夠輕鬆地指向這個文本文件路徑,無論我的PHP調用腳本來自哪裏。

我試圖改變$ filename ='logfile/testing_randomstring.txt'; writetologfile函數內部通過它執行到絕對路徑修復, 類似$文件名=「/ R /管理/日誌/ testing_randomstring.txt」, 但它不工作

回答

0

而不是使用相對路徑,你可以指定絕對路徑。假設public_html是在你的主目錄,試試這個:

$filename = '/public_html/r/admin/logfile/testing_randomstring.txt'; 
fopen(getenv('HOME') . $filename, 'a'); 

這使用getenv讀取環境變量$HOME的內容。

相關問題