Advertisement
kxphotographer

Counter.php

Jan 26th, 2015
243
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.09 KB | None | 0 0
  1. <?php
  2.  
  3. class Counter{
  4.     private $counterFileName;
  5.  
  6.     public function __construct($inFN){
  7.         if(!file_exists($inFN)){
  8.             $counterFilePointer = fopen($inFN, 'w');
  9.             flock($counterFilePointer, LOCK_EX);
  10.             fwrite($counterFilePointer, '0');
  11.             flock($counterFilePointer, LOCK_UN);
  12.             fclose($counterFilePointer);
  13.         }
  14.         $this->counterFileName = $inFN;
  15.     }
  16.     public function getCount(){
  17.         if($counterFilePointer = fopen($this->counterFileName, 'r')){
  18.             flock($counterFilePointer, LOCK_SH);
  19.             $count = (int)fgets($counterFilePointer);
  20.             flock($counterFilePointer, LOCK_UN);
  21.             fclose($counterFilePointer);
  22.             return $count;
  23.         }else{
  24.             throw new Exception("ファイルオープン失敗");
  25.         }
  26.     }
  27.     public function incrementCount($val = 1){
  28.         $count = $this->getCount() + $val;
  29.         if($counterFilePointer = fopen($this->counterFileName, 'w')){
  30.             flock($counterFilePointer, LOCK_EX);
  31.             fwrite($counterFilePointer, $count);
  32.             flock($counterFilePointer, LOCK_UN);
  33.             fclose($counterFilePointer);
  34.             return $count;
  35.         }else{
  36.             throw new Exception("ファイルオープン失敗");
  37.         }
  38.     }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement