jadrijan
jadrijan

Reputation: 1446

PHP concurrent file copy

I am working on a PHP web application, my first web application. One of the processes needs to copy some text files to a destination directory. In the destination directory it will open the text files and show the output in the web browser. I am wondering what happens if two users at the same time initiate the process? Since the files MUST be copied to destination directory and read from there. Do I create a unique destination directory each time? How is this properly done?

Upvotes: 0

Views: 160

Answers (1)

Devon Bessemer
Devon Bessemer

Reputation: 35347

You could create a unique directory, it all depends on what your goal is. Do you want to allow two different users to execute it at the same time?

Databases are usually useful in these situations because they are made for concurrent activity and feature table or even row locking.

In this case if you wanted to prevent a second user from running the process at the same time, you could use a lock file:

  1. Create a lock file if it doesn't exist
  2. Run the processes
  3. Unlink the lock file

If the lock file exists, wait until it is unlinked (deleted), an example:

while (file_exists('file.lock')) {
   usleep(100000); // sleep 100ms
}
touch('file.lock');
// Execute processes here
unlink('file.lock');

Lock files are commonly used in filesystems and applications to prevent users from modifying a file at the same time or running more than one instance.

Upvotes: 1

Related Questions