PHP file Lock Write instance tutorial

Source: Internet
Author: User
Tags flock

PHP File Lock Write

PHP file Write method, should be multi-threaded write:

    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. }//
    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

where the flock (int $handle, int $operation) function operation handle must be a file pointer that has already been opened.

Operation can be one of the following values: To get a shared lock (read program), set operation to Lock_sh (the previous version of PHP 4.0.1 is set to 1). To obtain an exclusive lock (written program), set operation to LOCK_EX (2 in previous versions of PHP 4.0.1). To release the lock (either share or exclusive), set operation to Lock_un (3 in previous versions of PHP 4.0.1). If you do not want flock () to block when locked, Operation plus LOCK_NB (set to 4 in previous versions of PHP 4.0.1).

  • 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: 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.