1<?php
2
3// adapted from http://www.dreamincode.net/code/snippet1666.htm
4
5class Mutex {
6    private $filename = NULL;			// The file to be locked
7	private $locked = false;
8
9	/* Constructor */
10	function __construct($filename){
11		// Append '.lck' extension to filename for the locking mechanism
12		$this->filename = $filename . '.lock';
13	}
14
15	function __destruct() { $this->release(); }
16	/* Methods */
17
18	function acquire($block = true, $timeout = 1){
19		// Create the locked file, the 'x' parameter is used to detect a preexisting lock
20		global $ID;
21		global $USERINFO;
22		for ($i = 0; $i < $timeout; $i++) {
23			$fp = @fopen($this->filename, 'x');
24			// If an error occurs fail lock
25			if($fp && @fwrite($fp, $USERINFO['name'])) {
26				@fclose($fp);
27				$this->locked = true;
28				return true;
29			}
30			if (!$block) break;
31			sleep(1);
32		}
33		$this->locked = false;
34		return false;
35	}
36
37	function release(){
38		// Delete the file with the extension '.lck'
39		if ($this->locked) @unlink($this->filename);
40		global $ID;
41		$this->locked = false;
42	}
43}
44?>