PHP File: Locking and Unlocking File



PHP File Tips - Part 12: You can lock a file use flock() function. This function allows you to performe a simple reader/write model. Once a file is locked with flock(), other processing attempting to write to file have to wait until unlock. It avoid multiprocess at a file that can corrupt it.
<?php
$f = "test2.txt";

$fo = fopen($f, "wb+") or die("cannot open");

if(flock($fo, LOCK_EX)){
  fwrite($fo,"test add a 2 string") or die("cannot write to file");
  flock($fo, LOCK_UN);
}else{
  die("Cannot lock file");
}

fclose($fo);
echo "sucess";
?>


Series this article:
PHP File: 3 Way of Reading File
PHP File: Reading File at Particular Lines
PHP File: Reading File at Particular Byte Ranges
PHP File: Checking File or Directory
PHP File: Showing All File in A Directory
PHP File: Showing All Files and Folders in Particular Directory
PHP File: Retrieving File Statistic
PHP File: Retrieving More File Information
PHP File: Counting Lines in a File
PHP File: Counting Characters and Words in File
PHP File: Writing File
PHP File: Locking and Unlocking File
PHP File: Removing Lines From File
PHP File: Inserting Lines into a File


Tag: file, lock file, unlock file Category: PHP Basic Post : April 14th 2008 Read: 3,264 Bookmark and Share

blog comments powered by Disqus