如何动态创建目录?

时间:2016-01-06 21:43:22

标签: php

我有下面的代码,但我想从日期开始在动态创建的文件夹下编写该文件。所以它应该看起来像这个date / 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');
    }
    ?>

2 个答案:

答案 0 :(得分:1)

尝试

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

答案 1 :(得分: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');
    }
    ?>