PHP flock() Function and Example


 

PHP flock() Function and Example

In this part of the tutorial we will learn about the PHP flock() function in context of file handling. And also we will see the example related to the flock function

In this part of the tutorial we will learn about the PHP flock() function in context of file handling. And also we will see the example related to the flock function

Syntax
bool flock ( file_name ,lock [,block] )

  • It puts the locks on the file or remove the lock
  • It is used for the  simple reader/writer file  model

lock values are

  • LOCK_SH - It is Shared lock  for reader. Other processes can access  the file.
  • LOCK_EX - It is Exclusive lock for writer. It doesn't allow  other processes to access the file
  • LOCK_UN -It releases a shared or exclusive lock
  • LOCK_NB - It doesn't  block other processes when the file has lock


Example of PHP Flock() Function

Code for flock() function PHP

<?php
$file
= fopen("c:/rose1/ram.txt","w+");
if (flock($file,LOCK_SH))
 fwrite($file,"India is a great country");
else
echo
"locking  problem in file";
?>

Output
ram.txt is not cotaining any thing as LOCK_SH makes the lock for reader and doesn't allow for writing

Code

<?php
$file = fopen("c:/rose1/ram.txt","w+");
if
(flock($file,LOCK_EX))
 fwrite(
$file,"India is a great country");
else
echo
"locking  problem in file";
?>

Output

now ram.txt has India is a great country

Ads