flock() function in PHP


The flock() function locks or releases a file. The function returns TRUE on success and FALSE on failure.

Syntax

flock(file_pointer, operation, block)

Parameters

  • file_pointer − A file pointer for open file to lock or release.

  • operation − Specifies the lock to use:

    • LOCK_SH - Shared lock (reader)
    • LOCK_EX - Exclusive lock (writer)
    • LOCK_UN - Release a shared or exclusive lock
  • block − Set to 1 if the lock would block

Return

The flock() function returns.

  • TRUE on success
  • FALSE on failure

Example

<?php
   $file_pointer = fopen("new.txt","w+");
   // shared lock
   if (flock($file_pointer,LOCK_SH)) {
      fwrite($file_pointer,"Some content");
      flock($file_pointer,LOCK_UN);
   } else {
      echo "Locking of file shows an error!";
   }
   fclose($file_pointer);
?>

Output

TRUE

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 24-Jun-2020

728 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements