About file_put_contents concurrency solution in PHP

Source: Internet
Author: User
Tags flock
When using file_put_contents, you will encounter a concurrency problem. we have a variety of solutions for this problem. In fact, locking is a preferred solution for small Editors. Of course there are other solutions, the specifics are as follows: when using file_put_contents, we will encounter a concurrency problem. we have a variety of solutions for this problem. In fact, locking is a preferred solution for small series. Of course there are other solutions, the details are as follows.


Solution 1, File_put_contents high concurrency and exclusive lock

 

Data is left blank when file_put_contents is used to write data to files during high-concurrency access.

View official documents:

 

Int file_put_contents (string $ filename, string $ data [, int $ flags [, resource $ context])
Parameters:

 

File name of the data to be written to filename. The data to be written. The type can be string, array, or stream resources (as mentioned above ). Flags can be FILE_USE_INCLUDE_PATH, FILE_APPEND and/or LOCK_EX (get an exclusive lock). However, be cautious when using FILE_USE_INCLUDE_PATH. A context resource.
An exclusive lock can be obtained directly until the flags parameter is LOCK_EX in high concurrency.

In addition, the flock function also provides the file locking method:


$ Fp = fopen ("/tmp/lock.txt", "w +"); if (flock ($ fp, LOCK_EX )) {// lock fwrite ($ fp, "Write something here \ n"); flock ($ fp, LOCK_UN ); // release lock} else {echo "Couldn't lock the file! ";} Fclose ($ fp );

Note that flock () requires a file pointer.

 

Method 2, File_put_contents () has a high concurrency problem. The processing method in Smarty is as follows.


 


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.