2014-07-17 75 views
1

我正在WordPress上創建一個函數來獲取robots.txt文件的內容。如果該文件不存在,請使用默認內容創建它。我將用它作爲我的選項頁面。好了,這是我的代碼,它應該工作幾乎在創建文件,但它並不:PHP - 讀取和寫入TXT文件的函數

function get_robots($robots_file) { 

$robots_file = get_home_path() . 'robots.txt'; //The robots file. 
$dir = get_home_path(); //The root directory 

if(is_file($robots_file)){ 
    $handle = fopen($robots_file, "r"); 
    $robots_content = fread($handle, filesize($robots_file));   
    fclose($handle); 

} else { 
    $default_content = "User-agent: *\nDisallow:"; 
    chmod($dir, 0777); 
    $handle = fopen($robots_file, "w+"); 
    $robots_content = fwrite($handle, $default_content);   
    fclose($handle); 

} 

chmod($dir, 0744); 
return $robots_content; 

} 

我不知道問題是否is_file,或fopen($robots_file, "w+"(應該是「R」? )在else之後。我不確定權限。 777需要嗎? 744是默認的WordPress根目錄?

而且我使用return稍後將它用作變量;我想fopen已經在創建該文件。我對嗎?

在此先感謝。

+2

如果你想知道哪個函數參數使用,那麼你應該首先看看函數文檔:http://php.net/fopen他們在那裏清楚地記錄。哦,在目錄上執行chmod 744可能會讓所有其他用戶破解它。刪除目錄上的執行權限將刪除列出其內容的能力。它不會刪除讀取文件的能力,只要你知道文件名是 –

回答

2

首先,我會使用完全不同的功能,對於這種簡單的操作,您有file_put_contents()file_get_contents()

所以可以簡單的解決方法是:

function get_robots() { 

$robots_file = get_home_path() . 'robots.txt'; //The robots file. 


if(file_exists($robots_file)){ 
    return file_get_contents($robots_file); 

} else { 
    $default_content = "User-agent: *\nDisallow:"; 
    file_put_contents($robots_file, $default_content); 
    return $default_content; 
} 

} 

我看不出任何一點通過$robots_file作爲函數的參數,所以我刪除它。你應該檢查這段代碼是否簡單。

我也看不出有什麼理由改變你在代碼中顯示的$dir權限。它應該是手動設置的,你絕對不應該在這個函數中改變你的根目錄權限。

編輯

由於此功能使用get_home_path()這一個可用大概只有你所要做的是在不同的方式管理面板上。您可以將下面的代碼添加到您的index.php文件的末尾:

function get_robots($path) 
{ 
    $robots_file = $path . DIRECTORY_SEPARATOR . 'robots.txt'; //The robots file. 
    if(file_exists($robots_file)){ 
     return file_get_contents($robots_file); 

    } else { 
     $default_content = "User-agent: *\nDisallow:"; 
     file_put_contents($robots_file, $default_content); 
     return $default_content; 
    } 
} 

get_robots(getcwd()); 

(當然,如果你願意,你可以移動get_robots()功能,其他一些文件

然而,你應該考慮本。是最好的方法,每次你的網站被瀏覽時,你都會運行這個功能,而且它很浪費(實際上你可能只想創建robots.txt文件一次),例如你可以創建robots.php文件,如果你想運行它你可以運行http://yourwordpressurl/robots.php。這當然是你的電話。

+0

謝謝Marcin。我想加載代碼文件應該創建,因爲它不存在,但它不工作。代碼位於functions.php(WordPress)上。在本地主機上測試它。 – Gerard

+0

你是否在任何地方運行此功能?你需要添加'get_robots();'執行這個功能 –

+0

Omg,那是很大的失敗xD。順便說一句,它返回'致命的錯誤:調用未定義的函數get_home_path()'。 – Gerard