2012-11-14 23 views
39

我上傳了很多來自網站的圖片,並且需要以更好的方式組織文件。 因此,我決定按月創建一個文件夾。當我運行file_put_contents()時創建一個文件夾

$month = date('Yd') 
file_put_contents("upload/promotions/".$month."/".$image, $contents_data); 

我試過這個之後,我得到了錯誤的結果。

消息:file_put_contents(上傳/促銷/ 201211/ang232.png):未能打開流:沒有這樣的文件或目錄

如果我試圖把文件只存在於文件夾,它的工作。但是,它未能創建一個新的文件夾。

有沒有辦法解決這個問題?

回答

97

file_put_contents()不創建目錄結構。只有文件。

您需要爲腳本添加邏輯以測試月份目錄是否存在。如果不是,請首先使用mkdir()

if (!is_dir('upload/promotions/' . $month)) { 
    // dir doesn't exist, make it 
    mkdir('upload/promotions/' . $month); 
} 

file_put_contents('upload/promotions/' . $month . '/' . $image, $contents_data); 

更新:mkdir()接受的$recursive第三個參數,這將創造任何丟失的目錄結構。如果您需要創建多個目錄,可能會很有用。

與設置爲777遞歸和目錄權限實施例:

mkdir('upload/promotions/' . $month, 0777, true); 
+1

太棒了!謝謝! – Jake

5

修改上面的回答的,使其更稍微通用的,(自動檢測並從系統的任意文件名創建文件夾斜槓)

ps先前的回答很棒

/** 
* create file with content, and create folder structure if doesn't exist 
* @param String $filepath 
* @param String $message 
*/ 
function forceFilePutContents ($filepath, $message){ 
    try { 
     $isInFolder = preg_match("/^(.*)\/([^\/]+)$/", $filepath, $filepathMatches); 
     if($isInFolder) { 
      $folderName = $filepathMatches[1]; 
      $fileName = $filepathMatches[2]; 
      if (!is_dir($folderName)) { 
       mkdir($folderName, 0777, true); 
      } 
     } 
     file_put_contents($filepath, $message); 
    } catch (Exception $e) { 
     echo "ERR: error writing '$message' to '$filepath', ". $e->getMessage(); 
    } 
} 
+2

絕對不必要的......你可以檢查目錄是否存在。如果不調用'mkdir($ fileDestinationDir,0777,true);'。然後調用'file_put_contents'。當* NIX系統使用'/'作爲目錄分隔符時,Windows並不關心,你可以毫無問題地執行'mkdir('/ path/with/forward/slashes')'。 –

+0

酷,好點,添加遞歸標誌 – aqm

-3

我寫了一個你可能喜歡的函數。它被稱爲forceDir()。它基本上檢查你想要的目錄是否存在。如果是這樣,它什麼都不做。如果沒有,它會創建目錄。使用這個函數的原因,而不僅僅是mkdir,這個函數也可以創建nexted文件夾。例如('upload/promotions/januari/firstHalfOfTheMonth')。只需將路徑添加到所需的dir_path即可。

function forceDir($dir){ 
    if(!is_dir($dir)){ 
     $dir_p = explode('/',$dir); 
     for($a = 1 ; $a <= count($dir_p) ; $a++){ 
      @mkdir(implode('/',array_slice($dir_p,0,$a))); 
     } 
    } 
} 
+3

你也可以只添加'true'作爲mkdir()的第三個參數。 – rjmunro

相關問題