views:

57

answers:

2

My PHP script serves files using readfile() and manually added HTTP headers. Files are about ~1 MB big, so no partial-reading is necessary.

What is the best way to replace this file with a updated one, but ensure already started downloads won't be broken? I'd like pending downloads to be finished with fetched old file version.

Platform: Linux, PHP 5, Apache 2.

+1  A: 

You could use flock to get a lock on the file handle - this will mean you writer process will block until it is able to get an exclusive lock.

So, your readers would obtain a LOCK_SH shared lock, and then simply use fpassthru to output the file, and finally release the lock.

The write would obtain a LOCK_EX exclusive lock, perform the write in safety, and then release the lock allowing any blocked readers to start fetching the new file.

Paul Dixon
But on a heavily loaded site you'll never get an exclusive lock
symcbean
+1  A: 

Use version numbering in the filename:

$candidates=sort(glob($dir . $prefix . '*'));
$most_recent=array_pop($candidates);

e.g. file0001.pdf file0002.pdf file0003.pdf

C.

symcbean
Simple yet great :-)
tomash