PHP file lock write instance Parsing

Source: Internet
Author: User
Tags flock
This article mainly introduces the PHP file locking and writing instance parsing. For more information, see

This article mainly introduces the PHP file locking and writing instance parsing. For more information, see

This document describes how to write PHP files to multiple threads. The Code is as follows:

Function file_write ($ file_name, $ text, $ mode = 'A', $ timeout = 30) {$ handle = fopen ($ file_name, $ mode ); while ($ timeout> 0) {if (flock ($ handle, LOCK_EX) {// arrange its locking $ timeout --; sleep (1 );}} if ($ timeout> 0) {fwrite ($ handle, $ text. '\ n'); flock ($ handle, LOCK_UN); fclose ($ handle); // return true;} return false ;}

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

Operation can be one of the following values:

To obtain the shared lock (read Program), set operation to LOCK_SH (PHP 4.0.1 and earlier versions to 1 ).
To obtain an exclusive lock (Write Program), set operation to LOCK_EX (set to 2 in versions earlier than PHP 4.0.1 ).
To release the lock (whether shared or exclusive), set operation to LOCK_UN (3 in PHP versions earlier than 4.0.1 ).
If you do not want flock () to be blocked during the lock, add LOCK_NB to operation (set to 4 in versions earlier than PHP 4.0.1 ).

In addition, fclose () is used to release the lock operation and is called when the code is executed.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.