user1032531
user1032531

Reputation: 26331

Save file to memory and later write back

I wish to read a file using PHP, and later write it to a directory which doesn't exist at the time of reading the file. I can't create the directory first as described below. I do not wish to save it in a temporary directory to prevent possible overwrites. Am I able to read the file, save it in memory, and later write the file?

WHY I WISH TO DO THIS: I have the following method which empties a directory. I now have a need to do so but keep one file in the root of the emptied directory. I recognize I could modify this method to do so, but I rarely need to do so, and may wish another approach. Instead, before calling this method, I would like to copy the file in question, empty the directory, and then put it back.

/**
* Empty directory.  Include subdirectories if $deep is true
*/
public static function emptyDir($dirname,$deep=false)
{
    $dirname=(substr($dirname, -1)=='/')?$dirname:$dirname.'/';
    if(!is_dir($dirname)){return false;}
    // Loop through the folder
    $dir = dir($dirname);
    while (false !== $entry = $dir->read())
    {
        // Skip pointers
        if ($entry == '.' || $entry == '..') {
            continue;
        }
        elseif(is_file($dirname.$entry)) {
            unlink($dirname.$entry);
        }
        elseif($deep && is_dir($dirname.$entry)){
            self::deltree($dirname.$entry);
        }
    }
    // Clean up
    $dir->close();
    return true;
}

Upvotes: 0

Views: 1166

Answers (3)

guitartowers.de
guitartowers.de

Reputation: 63

You can use the session to save the needed information.

Upvotes: 0

vaso123
vaso123

Reputation: 12391

Yes, it could be done. Just add a property to your class. So in your class property, there will be the content of the file, while the object is exists, and it did set. It could be a class variable (static) also, so you do not need to instantiate if you do not want.

class anything {

    var $fileContent = '';

    public static function emptyDir($dirname,$deep=false) {
        //....
    }

    public function setFileContent($fileOrUrlToRead) {
        $this->fileContent = file_get_contents($fileOrUrlToRead);
    }

    public function saveFile($fileName) {
        file_put_contents($fileName, $this->fileContent);
    }
}

$anything = new anything();
$anything->setFileContent('url_or_path_of_file_to_get');
anything::emptyDir('./media/files/');
$anything->saveFile('./media/files/something.txt');

Upvotes: 1

Steve
Steve

Reputation: 20469

Provided this is all done withing the same request, then yes you can. Just save the file contents to a variable, then write it back again:

$temp = file_get_contents('path/to/file.ext');

className::emptyDir($dir);

file_put_contents('path/to/file.ext', $temp);

Upvotes: 2

Related Questions