Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP lock text file for editing?

I've got a form that writes its input to a textfile. Would it be possible to lock a text file for editing, and perhaps give a friendly message "the file is edited by another user, please try again later."

I'd like to avoid conflicts if the file has multiple editors at the same time.

Here's how the entry is currently added.

$content = file_get_contents("./file.csv");
$fh = fopen("./file.csv", "w");
fwrite($fh, $date_yy . '-' . $date_mm . '-' . $date_dd . '|' . $address . '|' . $person . '|' . $time_hh . ':' . $time_mm);
fwrite($fh, "\n" . $content);
fclose($fh);

Any thoughts?

like image 979
Janne Avatar asked Mar 15 '13 15:03

Janne


People also ask

How do I lock a file for editing?

Right-click a file (or click the ellipses (...)) to open the More Options menu. Click Lock. Choose a duration for the lock.

What is the use of flock function?

flock() allows you to perform a simple reader/writer model which can be used on virtually every platform (including most Unix derivatives and even Windows). The lock is released also by fclose(), or when stream is garbage collected.


1 Answers

You can use flock() function to lock the file. For more see this

Something like:

   <?php

      $content = file_get_contents("./file.csv");
      $fp = fopen("./file.csv", "w"); // open it for WRITING ("w")
      if (flock($fp, LOCK_EX)) 
      {
      // do your file writes here
      fwrite($fh, $date_yy . '-' . $date_mm . '-' . $date_dd . '|' . $address . '|' .  $person . '|' . $time_hh . ':' . $time_mm);
      fwrite($fh, "\n" . $content);
      fclose($fh);
      flock($fh, LOCK_UN); // unlock the file
      } 
   ?> 
like image 121
Emmanuel N Avatar answered Sep 22 '22 16:09

Emmanuel N