本文以實例講述了PHP文件寫入方法,以應對多線程寫入,具體代碼如下:
function file_write($file_name, $text, $mode='a', $timeout=30){
$handle = fopen($file_name, $mode);
while($timeout>0){
if ( flock($handle, LOCK_EX) ) { // 排它性的鎖定
$timeout--;
sleep(1);
}
}
if ( $timeout > 0 ){
fwrite($handle, $text.'\n');
flock($handle, LOCK_UN);
fclose($handle); //釋放鎖定操作
return true;
}
return false;
}
其中flock(int $handle, int $operation)函數操作的 handle 必須是一個已經打開的文件指針。
operation 可以是以下值之一:
要取得共享鎖定(讀取的程序),將 operation 設為 LOCK_SH(PHP 4.0.1 以前的版本設置為 1)。
要取得獨占鎖定(寫入的程序),將 operation 設為 LOCK_EX(PHP 4.0.1 以前的版本中設置為 2)。
要釋放鎖定(無論共享或獨占),將 operation 設為 LOCK_UN(PHP 4.0.1 以前的版本中設置為 3)。
如果不希望 flock() 在鎖定時堵塞,則給 operation 加上 LOCK_NB(PHP 4.0.1 以前的版本中設置為 4)。
此外, fclose()用來釋放鎖定操作,在代碼執行完畢時調用。