且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用fwrite将文件保存到新目录

更新时间:2023-12-04 13:02:04

您应该检查该文件夹是否存在,如果不存在,请创建该文件夹.您的代码应如下所示:

You should check that folder exists and if not to create it. Your code should look like:

<?php

function saveFile($filename,$filecontent){
    if (strlen($filename)>0){
        $folderPath = 'temp';
        if (!file_exists($folderPath)) {
            mkdir($folderPath);
        }
        $file = @fopen($folderPath . DIRECTORY_SEPARATOR . $filename,"w");
        if ($file != false){
            fwrite($file,$filecontent);
            fclose($file);
            return 1;
        }
        return -2;
    }
    return -1;
}

?>

我还改进了代码的另一部分,以避免在出现问题时多次调用该函数.

Also I've improved another part of your code to avoid multiple calls to the function if something goes wrong.

<?php
        $fileSavingResult = saveFile($filename, $filecontent);
        if ( fileSavingResult == 1){
            echo "<tr><td><br/>File was saved!<br/><br/></td></tr>";
        } else if (fileSavingResult == -2){
            echo "<tr><td><br/>An error occured during saving file!<br/><br/></td></tr>";
        } else if (fileSavingResult == -1){
            echo "<tr><td><br/>Wrong file name!<br/><br/></td></tr>";
        }

?>