質問

due to the fact how a Server can handle requests (-> Simultaneous Requests to PHP Script), I have a question about what can happen, if a script checks a filename and then saves the file.

For example: User A requests "save.php". A really short time later User B requests "save.php". The script of User A is at the point where the script checks if the file exists. The file does not exist and BEFORE the file is written, User B's script is at the point where it checks the existing of the file. So it also says that the file does not exist. Now User A's script writes the file. And User B's script overwrites the file, if they have the same filename. (Filename is random, but this can happen).

How can I avoid such things? Is there something like Tablelocking and Transactions for PHP-command? Is it possible that User B's script outruns User A's script, because it gets more ressources from the server?

Best regards

役に立ちましたか?

解決

Please have a look at:

http://www.php.net/manual/en/function.fopen.php

You need to use exclusive locking while creating the the file like this:

$handle = fopen("/home/somewhere/yourfile.txt", "x");

When you do it like this the secondary access attempts (user B, C) to the file will return false and generate a warning since the file is created and exclusively locked by user A.

As soon as file is created file_exists will be true but the other users can not fopen it because it will be created with an exclusively locked state.

When user A finishes his/her job, the later invocations can access the file

Manual entry for modes x and x+ are as follows:

'x'

Create and open for writing only; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call.

'x+'

Create and open for reading and writing; otherwise it has the same behavior as 'x'.

他のヒント

Use a semaphore if your php installation supports it : http://be2.php.net/manual/en/ref.sem.php

Alternatively you can also check the flock() function : http://be2.php.net/manual/en/function.flock.php

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top