我正在使用一個非常簡單的腳本,其中一些用戶資料存盤在資料庫旁邊的文本檔案中,因為該檔案需要由系統上的特定行程讀取。
以下格式的一行的php過期日期更新代碼如下:
U: w w { enddate=2022-10-18 }
功能代碼如下:
$date = "enddate=";
$date .= setExpireDate($duration);
$Read = file($fileDir);
foreach ($Read as $LineNum => $line) {
$LineParts = explode(' ', $line);
if (count($LineParts) == 1) {continue;}
if ($LineParts[1] == $username) {
$LineParts[4] = $date;
$Read[$LineNum] = implode(' ', $LineParts);
break;
}
}
file_put_contents($fileDir, $Read, LOCK_EX);
一些用戶報告了問題,經過一番搜索,我發現資料庫中的資料更新正常,但文本檔案中的資料沒有更新,因為某些用戶的資料沒有更新。
因為我認為這是一個檔案鎖定問題,這會阻止一些負載過重的用戶在檔案上寫入,但資料庫可以處理多次寫入就好了。
那么有沒有比這更好地同時處理檔案上的多個寫入?
有沒有辦法在 php 中模擬這一點,比如通過表單提交鎖定檔案?
我試過這個:
function lock(){
$fp = fopen("file.txt", "r ");
flock($fp, LOCK_EX);
echo "file is locked <br>";
}
但它根本不起作用,其他人可以寫入檔案。
PS:我知道有很多關于檔案鎖定的問題,但沒有一個答案有幫助!
問候
uj5u.com熱心網友回復:
這是檔案鎖定方法的示例
首先,您嘗試鎖定 Lock 檔案,如果您能一切順利,繼續編輯真實檔案。如果您無法獲得鎖定,請重試直到可以獲得。
// this is not the file you are attempting to update, its just the lock file
// it must already exist and its bext if you place it in a specific directory,
// not accessable from the web.
$fplock = fopen("/some/path/lock.txt", "r ");
// attempt to get an exclusive lock on the lock file
while ( ! flock($fplock, LOCK_EX) ) {
// this has failed to get the lock so do nothing but retry,
// it should be only milli seconds until the other process finishes
// and releases the lock
}
// the lock must have been released by the other process when you get here
// or you got a lock on your first attempt and never ran the wait loop
// at this point this script has the lock
$date = "enddate=";
$date .= setExpireDate($duration);
$Read = file($fileDir);
foreach ($Read as $LineNum => $line) {
$LineParts = explode(' ', $line);
if (count($LineParts) == 1) {continue;}
if ($LineParts[1] == $username) {
$LineParts[4] = $date;
$Read[$LineNum] = implode(' ', $LineParts);
break;
}
}
file_put_contents($fileDir, $Read, LOCK_EX);
/*
closing the lock file has the effect of releasing the lock, or simply finishing this
script will do the same, but do it yourself as soon as you have finished updating the
real file, so other process's dont have to wait until the script finishes,
I assume you may have other code after this
*/
fclose($fplock);
當然,所有訪問真實檔案的腳本也必須在訪問真實檔案之前嘗試鎖定鎖定檔案,否則這一切都會一團糟。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/520832.html
標籤:php文件锁定
