Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform filesystem operations in transaction with php?

I am looking for ways to implement filesystem operations using php with transaction support. Like if I am performing operations like move, copy and delete inside a transaction, if one of them fails, the script needs to revert all those operations already performed. I am kind of clueless and am seeking guidance how it can be achieved. And if available libraries or solutions exists? I apologize if the question sounds vague.

like image 604
Nitesh Avatar asked Feb 27 '13 11:02

Nitesh


People also ask

What are transaction based file systems and its operations?

A transactional file system wherein multiple file system operations may be performed as a transaction. An application specifies that file system-related operations should be handled in a transaction, and the application is given a file handle associated with a transaction context.

Which function is used to get all file information?

The file_get_contents function is used to read the entire file contents. The code below illustrates the implementation. The difference between file_get_contents and fgets is that file_get_contents returns the file data as a string while fgets reads the file line by line.


2 Answers

The most common pattern for this is copying everything to somewhere else, operate on the copy and replace the originals if everything goes right.

Something tells me that PHP stream wrappers could be useful for this as well. It is possible to override the 'file://' protocol and operate in a virtual filesystem (proof of concept: https://github.com/Respect/Test#streamwrapper).

like image 76
alganet Avatar answered Sep 18 '22 13:09

alganet


Filesystems - in contrast to database management systems - do not support transactions. However some do provide the things you need to implement transactions; that is locking and logging. Logging will not be your problem because you can do it in php, too, but you'll need a filesystem that provides file locks.

I recommend you not to implement anything like this youself - there are lot of problems you might encounter. The database guys look back on a research history of decades, here.

But if you have to, you could (for a start) implement something like Two-phase locking in php. Also, you might consider using the command pattern, that helps with undo functionality for your rollback.

like image 33
Francois Bourgeois Avatar answered Sep 16 '22 13:09

Francois Bourgeois