John Davidson

php - Allow 1 access at a time using fopen()

0 comments
Message:


I'd like to allow 1 access at a time to a .txt file until the script finishes, so that it shows the message "Busy" when I open the same PHP again.


I have tried this:


<?php
$file = fopen('file.txt', 'w+');
if (flock($file, LOCK_EX)) {sleep(60); flock($file, LOCK_UN);}
else {echo 'Busy';}
fclose($file);

However it never shows the "Busy" message. Every new tab I open is in "sleep" mode. What am I doing wrong?



My Answer:
"File is currently in use, please try again later" if another user tries to access the file while it is already being used.

You can achieve this by using a lock file. Here's an example code snippet:

php
$lockFile = fopen("lock.txt", "w");

if (flock($lockFile, LOCK_EX)) {
$file = fopen("data.txt", "r");

// Your code to read/write to the file goes here

flock($lockFile, LOCK_UN);
} else {
echo "File is currently in use, please try again later";
}

fclose($lockFile);


In this code, we first create a lock file "lock.txt" and acquire an exclusive lock on it using `flock($lockFile, LOCK_EX)`. If the lock is successfully acquired, we can then proceed to open and read/write to the actual data file "data.txt". Once we are done with the file operations, we release the lock using `flock($lockFile, LOCK_UN)`.

If another user tries to access the file while it is already in use, they will see the message "File is currently in use, please try again later".

Rate this post

5 of 5 based on 4141 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us