<?php 

function createLockFile ($lockFilePrefix, $maxReach, $timeToUnlock, $colSep = '|') 
{
	$currentTimeStamp = time();
	$filePath = $lockFilePrefix.'_lock';
	$fileExisted = file_exists($filePath);
	$content = '';
	$lastTimeLock = '';
	$lockCount = 0;
	$isLocked = 0;
	
	if ($fileExisted) {
		$content = file_get_contents($filePath);
	}
	
	if ($content != '') {
		list($lockCount, $lastTimeLock, $isLocked) = explode ($colSep, $content);
	}
	
	$timeDiffMin = $lastTimeLock != '' ? dateDifference(date('Y-m-d H:i:s',$currentTimeStamp), date('Y-m-d H:i:s',$lastTimeLock), '%i') : 0;
	
	
	if ($lockCount < $maxReach && $timeDiffMin < $timeToUnlock) {
		$lockCount ++;
		$isLocked = $lockCount < $maxReach ? 0:1;
	}
	else if ($timeDiffMin > $timeToUnlock) {
		$lockCount = 0;
		$isLocked = 0;
	}
	
	$lockTime = ($isLocked == 1) ? $lastTimeLock : $currentTimeStamp;
	$content = $lockCount . $colSep . $lockTime . $colSep . $isLocked;
	$fh = fopen ($filePath,'w');
	fwrite ($fh, $content);
	fclose ($fh);
	
	return $timeDiffMin;
}

function releaseLockFile ($lockFilePrefix) 
{
	$filePath = $lockFilePrefix.'_lock';
	$fileExisted = file_exists($filePath);
	if ($fileExisted) {
		unlink($filePath);
	}
}

function dateDifference($date_1 , $date_2 , $differenceFormat = '%a' )
{
	$datetime1 = date_create($date_1);
	$datetime2 = date_create($date_2);
	$interval = date_diff($datetime1, $datetime2);
	return $interval->format($differenceFormat);
}

$username = '0988568786';
$maxReach = 3;
$timeToUnlock = 1;
echo createLockFile($username, $maxReach, $timeToUnlock);
releaseLockFile ($username);


