[473] | 1 | <?php
|
---|
| 2 |
|
---|
[620] | 3 | function createLockFile ($lockFilePrefix, $maxReach, $timeToUnlock, $colSep = '|')
|
---|
| 4 | {
|
---|
| 5 | $currentTimeStamp = time();
|
---|
| 6 | $filePath = $lockFilePrefix.'_lock';
|
---|
| 7 | $fileExisted = file_exists($filePath);
|
---|
| 8 | $content = '';
|
---|
| 9 | $lastTimeLock = '';
|
---|
| 10 | $lockCount = 0;
|
---|
| 11 | $isLocked = 0;
|
---|
| 12 |
|
---|
| 13 | if ($fileExisted) {
|
---|
| 14 | $content = file_get_contents($filePath);
|
---|
| 15 | }
|
---|
| 16 |
|
---|
| 17 | if ($content != '') {
|
---|
| 18 | list($lockCount, $lastTimeLock, $isLocked) = explode ($colSep, $content);
|
---|
| 19 | }
|
---|
| 20 |
|
---|
| 21 | $timeDiffMin = $lastTimeLock != '' ? dateDifference(date('Y-m-d H:i:s',$currentTimeStamp), date('Y-m-d H:i:s',$lastTimeLock), '%i') : 0;
|
---|
| 22 |
|
---|
| 23 |
|
---|
| 24 | if ($lockCount < $maxReach && $timeDiffMin < $timeToUnlock) {
|
---|
| 25 | $lockCount ++;
|
---|
| 26 | $isLocked = $lockCount < $maxReach ? 0:1;
|
---|
| 27 | }
|
---|
| 28 | else if ($timeDiffMin > $timeToUnlock) {
|
---|
| 29 | $lockCount = 0;
|
---|
| 30 | $isLocked = 0;
|
---|
| 31 | }
|
---|
| 32 |
|
---|
| 33 | $lockTime = ($isLocked == 1) ? $lastTimeLock : $currentTimeStamp;
|
---|
| 34 | $content = $lockCount . $colSep . $lockTime . $colSep . $isLocked;
|
---|
| 35 | $fh = fopen ($filePath,'w');
|
---|
| 36 | fwrite ($fh, $content);
|
---|
| 37 | fclose ($fh);
|
---|
| 38 |
|
---|
| 39 | return $timeDiffMin;
|
---|
| 40 | }
|
---|
[473] | 41 |
|
---|
[620] | 42 | function releaseLockFile ($lockFilePrefix)
|
---|
| 43 | {
|
---|
| 44 | $filePath = $lockFilePrefix.'_lock';
|
---|
| 45 | $fileExisted = file_exists($filePath);
|
---|
| 46 | if ($fileExisted) {
|
---|
| 47 | unlink($filePath);
|
---|
| 48 | }
|
---|
| 49 | }
|
---|
[473] | 50 |
|
---|
[620] | 51 | function dateDifference($date_1 , $date_2 , $differenceFormat = '%a' )
|
---|
[473] | 52 | {
|
---|
[620] | 53 | $datetime1 = date_create($date_1);
|
---|
| 54 | $datetime2 = date_create($date_2);
|
---|
| 55 | $interval = date_diff($datetime1, $datetime2);
|
---|
| 56 | return $interval->format($differenceFormat);
|
---|
[473] | 57 | }
|
---|
| 58 |
|
---|
[620] | 59 | $username = '0988568786';
|
---|
| 60 | $maxReach = 3;
|
---|
| 61 | $timeToUnlock = 1;
|
---|
| 62 | echo createLockFile($username, $maxReach, $timeToUnlock);
|
---|
| 63 | releaseLockFile ($username);
|
---|
| 64 |
|
---|
| 65 |
|
---|