Saving file into new directory using fwrite

Woody picture Woody · Aug 31, 2016 · Viewed 10k times · Source

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.

Answer

Andrej Ludinovskov picture Andrej Ludinovskov · Aug 31, 2016

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

?>