Question

I know there is a function to create a temporary file, but that's not what I want to do. I want to temporarily write changes to a file that exists and will continue to exist, and then remove those changes later. I know I could fopen, fwrite, fclose. I can write, and then use regex to remove those changes later, but I was wondering if there was a better way. If not tell me so and I'll close the question.

Thanks

Was it helpful?

Solution

I would create a temporary version of the file (either by directly copying it or by using another method), add whatever you'd like to it, then delete the copy when you're done with it, and use the original file again. This seems safer because it ensures that you keep the original version of the file intact, instead of modifying the file and potentially making mistakes trying to dynamically revert it.

OTHER TIPS

You could utilize ftruncate().

Keep your original $size = filesize($fn) before appending to your file. When you're done and want to revert to the original state, open the file again, then ftruncate($f, $size) to the previous state.

Commonly you would rather use a temporary file.

If your interested in creating a 'history' database of your files, you could edit the document and when you click save, it creates a new version of the document with the appended changes and adds the filename to the database with the edited date?

This way whenever you make a change to the document, the first document stays intact, and you can revert changes you've made previously. To make it more thorough, you could add an expiry date to each change so they expire over time and your server HD doesn't fill up like mad when you make small changes.

EDIT: Though this really depends on how long you want to keep the changes. If your planning on keeping the changes to the files for an extended period of time, I would use a database that is filled with each duplicated filename with it's edited date.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top