Lock or release a file in PHP

Description

The following code shows how to lock or release a file.

Example


<?php//  w  w  w  .  ja  v a 2 s  .  c om
    
    $file = fopen("test.txt","w+");
    
    // exclusive lock
    if (flock($file,LOCK_EX)){
       fwrite($file,"this is a test");
       // release lock
       flock($file,LOCK_UN);
    }else{
       echo "Error locking file!";
    }
    
    fclose($file);

/*
Possible values:     
LOCK_SH - Shared lock (reader). Allow other processes to access the file 
LOCK_EX - Exclusive lock (writer). Prevent other processes from accessing the file 
LOCK_UN - Release a shared or exclusive lock 
LOCK_NB - Avoids blocking other processes while locking 

*/
?>




















Home »
  PHP Tutorial »
    File »




Directory
DirectoryIterator
Drive
File
File Permission
File Read Save
FileSystemIterator
Path
Zip