PHP flock() to lock a file when a process is running

Suppose you want to prevent a process to run again if it is already in running state, then you need some kind of checks to tell if the process is already running. One way to accomplish this is to use a lock. Every time before starting the process, check if the lock is locked, only start the process if the lock is open. If the lock is open, then starts the process and lock the lock. Release the lock until the process is finished. PHP flock() is a function that you can use to lock a file. You can use a file as a lock, and use flock() as a key to lock and unlock the file.

php_flock.html, the code below contains the html and javascript. It creates a button, when the button is clicked it will make a ajax call to run a php script. When the php script started, it checks if the file process_lock is locked or not, if it is not locked, then it starts the process, sleeps for 10 seconds, and then releases the lock. If it is locked, it will return the message saying the process is in running state and the message will shop up in the javascript alert.

<!DOCTYE html>
<html>
	<head>
		<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
		<script type='text/javascript'>
			$(document).ready(function(){
				$('#aBtn').click(function(){
				$.ajax({
			           url:    'php_flock.php',
			           success: function(data,status) {
			                        alert(data);
			                    },
			           async:   true
			        });
				});
			});
		</script>
	</head>
	<body>
		<button id='aBtn' style="cursor:pointer">Start some process</button>	
	</body>
</html>

php_flock.php

<?php
ignore_user_abort();
$file = fopen("process_lock","r+");

// exclusive lock, LOCK_NB serves as a bitmask to prevent flock() to block the code to run while the file is locked.
// without the LOCK_NB, it won't go inside the if block to echo the string
if (!flock($file,LOCK_EX|LOCK_NB))
{
  	echo "Unable to obtain lock, the previous process is still going on."; 
}
else
{
	//Lock obtained, start doing some work now
	sleep(10);//sleep for 10 seconds

	echo "Work completed!";
	 // release lock
	flock($file,LOCK_UN);
}

fclose($file);

process_lock, an empty file. You can create it by this command on unix like system.

touch process_lock #creates the file
chmod 777 process_lock #grants read, write, and execute to all users.

Use case 1:
Click the button, wait for 10 seconds. You will get an alert message saying “Work completed!”

Use case 2:
Click the button, refresh the page and click the button again within 10 seconds. You will get an alert message saying “Unable to obtain lock, the previous process is still going on.”

Search within Codexpedia

Custom Search

Search the entire web

Custom Search