Saving file into new directory using fwrite

百般思念 提交于 2019-12-06 14:17:32

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>";
        }

?>
$tempFile = fopen( "temp/filename", "w" );
fwrite( $tempFile, $filecontent );
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!