filelock.php

Simple file locks for php
git clone git://git.finwo.net/lib/filelock.php
Log | Files | Refs | README | LICENSE

FileLock.php (2037B)


      1 <?php
      2 
      3 namespace Finwo\FileLock;
      4 
      5 class FileLock
      6 {
      7     /**
      8      * @var string
      9      */
     10     protected $filename = null;
     11 
     12     // 10 ms
     13     const LOCK_WAIT = 10000;
     14 
     15     /**
     16      * FileLock constructor.
     17      *
     18      * @param $filename
     19      */
     20     public function __construct( $filename )
     21     {
     22         $this->filename = $filename;
     23     }
     24 
     25     /**
     26      * @param int $hash
     27      *
     28      * @return resource
     29      */
     30     protected static function getResource( $hash )
     31     {
     32         static $resource = null;
     33         if(is_null($resource)) {
     34             $resource = sem_get($hash);
     35         }
     36         return $resource;
     37     }
     38 
     39     /**
     40      * @param string $filename
     41      *
     42      * @return bool
     43      */
     44     public static function _acquire( $filename )
     45     {
     46         if (function_exists('sem_get')) {
     47             @sem_acquire(self::getResource(hexdec(md5($filename))));
     48             return true;
     49         } else {
     50             // Generate filename
     51             $lockfile = $filename.'.lock';
     52 
     53             // Wait until lock expired or gone
     54             while(file_exists($lockfile)) {
     55                 $lockExpires = intval(@file_get_contents($lockfile));
     56                 if($lockExpires<time()) {
     57                     unlink($lockfile);
     58                 } else {
     59                     usleep(self::LOCK_WAIT);
     60                 }
     61             }
     62 
     63             // Create a lock
     64             return file_put_contents($lockfile, sprintf("%d",time()+5)) !== false;
     65         }
     66     }
     67 
     68     /**
     69      * @param string $filename
     70      *
     71      * @return bool
     72      */
     73     public static function _release( $filename )
     74     {
     75         if(function_exists('sem_get')) {
     76             @sem_release(self::getResource(hexdec(md5($filename))));
     77             return true;
     78         } else {
     79             return @unlink($filename.'.lock');
     80         }
     81     }
     82 
     83     /**
     84      * @return bool
     85      */
     86     public function acquire() {
     87         return self::_acquire($this->filename);
     88     }
     89 
     90     /**
     91      * @return bool
     92      */
     93     public function release() {
     94         return self::_release($this->filename);
     95     }
     96 
     97 
     98 }