PHP file lock writing example tutorial

WBOY
Release: 2016-07-25 09:11:58
Original
874 people have browsed it

php file lock writing

PHP file writing method, coping with multi-threaded writing:

  1. function file_write($file_name, $text, $mode='a', $timeout=30){
  2. $handle = fopen($file_name, $mode);
  3. while($ timeout>0){
  4. if ( flock($handle, lock_ex) ) {
  5. $timeout--;
  6. sleep(1);
  7. }
  8. } // bbs.it-home.org
  9. if ( $timeout > 0 ){
  10. fwrite($handle, $text.'n');
  11. flock($handle, lock_un);
  12. fclose($handle);
  13. return true;
  14. }
  15. return false;
  16. }
Copy code

The handle operated by flock(int $handle, int $operation) function must be an open file pointer.

operation can be one of the following values: To obtain a shared lock (reading program), set operation to lock_sh (set to 1 in versions prior to PHP 4.0.1). To obtain an exclusive lock (writing program), set operation to lock_ex (set to 2 in versions prior to PHP 4.0.1). To release a lock (whether shared or exclusive), set operation to lock_un (set to 3 in versions prior to PHP 4.0.1). If you don't want flock() to block on lock, add lock_nb (set to 4 in versions prior to PHP 4.0.1) to the operation.



source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!