PHP,在目录中创建文件

时间:2013-11-30 08:53:06

标签: php file text directory text-files

帮助!

所以我在堆栈溢出上看了很多解决方案,但似乎没有用。所以我正在做的是创建一个带有随机数的目录,然后在其中创建一个文本文件。

我的目录是这样的:

localhost
--/tdir/
---/(random number directory) < this is were i want to save to the text file

这是我的代码:

    <?php
            $dir = rand(1, 1999999);
            if (!file_exists($dir)) {
            mkdir($dir, 0777, true);
        }
            if ($dir == true) {
                echo "Created directory! :D";
            } else {
                echo "Failed to create directory! ~ :(";
            }

        chmod("/tdir/$dir/", 0777);
        echo "</br><a href='/tdir/'>Go Back</a>";
        echo "</br><a href='/tdir/$dir'>Go to page!</a></br>";
        $my_file = '../'.$dir.'/file.txt';
        $handle = fopen($my_file, 'w') or die('Cannot open file:  '.$my_file);
        $data = 'This is the data';
        fwrite($handle, $data);
    ?>

我一直收到这个错误:

Created directory! :D
Go Back
Go to page!
Cannot open file: ../1320710 *random number directory* /file.txt

我需要能够保存到$ dir目录中的file.txt!

1 个答案:

答案 0 :(得分:0)

你必须评估mkdir函数的响应,就像这样写

if (mkdir($dir, 0777, true) === TRUE){
....

此外,在编写/读取文件夹时,请确保使用系统路径,而不是URL路径。