What is the use of ‘flock’ in PHP [closed]

Tags: , ,

I am working on Codeigniter 3 for a month, and i want to make my own logging app, that logs the entry of the users and their actions on the website.So i digged deep into the codes related to logging in codeigniter and their i found a function ‘flock’ that made me curious. I tried to read about it on official php documentation website but didn’t found any satisfactory explanations. If someone can help me with this like why we use it and what are the real life implementations and use cases of this function, it would be a great help for me..!!



One of the problem when working with the file system in PHP is that after you start working on a file with fopen it is still possible for one or more scripts to update the same file,

That can cause several problems, just think if the same file is updated at the same time.

The flock() function in PHP locks the file, once opened, to avoid this problem. It also returns a boolean value depending on if the lock has been successfully or not.

flock() also uses different flags to set how the function has to work, they are:

  • LOCK_SH to acquire a shared lock (reader).
  • LOCK_EX to acquire an exclusive lock (writer).
  • LOCK_UN to release a lock (shared or exclusive).

Here is an example, hope it helps understand:

$fp = fopen("/tmp/lock.txt", "r+");

if (flock($fp, LOCK_EX)) {  // acquire an exclusive lock
   // update the file
} else {
    echo "Couldn't get the lock!";


more info in this post

Source: stackoverflow