Jump to content

Write to file sometimes deletes EVERYTHING, leaving empty file


wallaby

Recommended Posts

I've used PHP to save raw data from Flash to an XML in the past. Load the XML into flash, update a couple variables, then send it to PHP to completely overwrite the old .xml file. This works great most of time, but sometimes after a few days, I'll check the .xml and it will be empty (0 bytes). Not sure if this is caused by a user who aborted during the writing process, or simultaneous connections, etc. Been thinking about doing a backup every day using CRON, but that's a mission and I'd like for it not to happen full stop. Any suggestions?

I have no idea why it owuld just go this randomly, but you can try this:

 

<?php
// Delete below here if you have PHP 5
if (!function_exists('file_get_contents')) {
     function file_get_contents($file) {
          return implode("\n", file($file));
     }
}
// Delete above here if you have PHP 5

function writeContents($file, $contents) {
     $fHandle = fopen($file, "w");
     fwrite($fHandle, $contents);
     fclose($fHandle);
}

// Get the old file contents
$oldContents = file_get_contents("file.xml");
writeContents("file.xml", "new contents");

// Write old contents if it failed
if (!filesize("file.xml")) writeContents("file.xml", $oldContents);
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.