Saving file into new directory using fwrite

不羁岁月 提交于 2019-12-10 11:18:48

问题


I have a simple PHP script that writes a file into directory where located, but need to have it written into a directory called "temp".

There are many answers here on the subject, but can't seem to find what I need. Have reviewedhttp://us2.php.net/manual/en/function.fwrite.php with no luck.

Here is the basic PHP without the form part:

<?php

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

?>

This appears below the /form tag:

<?php    

    if (isset($_POST['submitBtn'])){
        $filename    = (isset($_POST['filename']))    ? $_POST['filename']    : '' ;
        $filecontent = (isset($_POST['filecontent'])) ? $_POST['filecontent'] : '' ;

?>

and then:

<?php

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

?>

Thanks for input.


回答1:


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

?>



回答2:


$tempFile = fopen( "temp/filename", "w" );
fwrite( $tempFile, $filecontent );


来源:https://stackoverflow.com/questions/39237958/saving-file-into-new-directory-using-fwrite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!