2016-01-06 49 views
2

我有下面的代碼,但我想從日期的動態創建的文件夾下寫入文件。因此,它應該是這樣的日期/ FILENAME.TXT如何動態創建目錄?

<?php 
    if(isset($_POST['field1']) && isset($_POST['field2'])) { 
     $data = $_POST['field1'] . '-' . $_POST['field2'] . "\n"; 
     $filename = date('YmdHis').".txt"; 
     if (!file_exists($filename)) { 
      $fh = fopen($filename, 'w') or die("Can't create file"); 
     } 
     $ret = file_put_contents($filename, $data, FILE_APPEND | LOCK_EX); 
     if($ret === false) { 
      die('There was an error writing this file'); 
     } 
     else { 
      echo "$ret bytes written to file"; 
     } 
    } 
    else { 
     die('no post data to process'); 
    } 
    ?> 

回答

0

您應該使用的mkdir函數來創建目錄:

<?php 
    if(isset($_POST['field1']) && isset($_POST['field2'])) { 
     $data = $_POST['field1'] . '-' . $_POST['field2'] . "\n"; 
     mkdir(date('YmdHis')); 
     $filename = date('YmdHis')."/filename.txt"; 
     if (!file_exists($filename)) { 
      $fh = fopen($filename, 'w') or die("Can't create file"); 
     } 
     $ret = file_put_contents($filename, $data, FILE_APPEND | LOCK_EX); 
     if($ret === false) { 
      die('There was an error writing this file'); 
     } 
     else { 
      echo "$ret bytes written to file"; 
     } 
    } 
    else { 
     die('no post data to process'); 
    } 
    ?> 
+0

伴侶好的嘗試,但我不想改變我的文件名我只想從日期添加目錄。所以輸出應該看起來像這個日期/日期.txt。 – BB1907

+0

date('YmdHis')。「/」。日期('YmdHis')。 「。文本」;喜歡這個? –

+0

YESSSSSSSSSS =)))非常感謝。我不知道如何使用「/」雙引號等等,所以我得到的語法錯誤,但你修復它=))大 – BB1907

1

if (!file_exists('path/to/directory')) { 
    mkdir('path/to/directory', 0777, true); 
} 
+0

謝謝,我應該用「日期('YMD')」這個「路徑/到/目錄」這個? – BB1907

+0

取決於你在哪個diretory存儲子目錄日期(Ymd) – scaisEdge

+0

我希望它是這樣的20160107/20160107.txt – BB1907