This article introduces the problem and solution of empty written data when using file_put_contents in PHP with high concurrency and exclusive locks. Friends in need can refer to it.
During high concurrent access, using file_put_contents to write files causes the data to be blanked. View official documentation: int file_put_contents ( string $filename , string $data [, int $flags [, resource $context ]] ) Parameters: filename The name of the file to which data is to be written. data The data to be written. The type can be string, array or stream resource (as mentioned above). flags Flags can be FILE_USE_INCLUDE_PATH, FILE_APPEND and/or LOCK_EX (to obtain an exclusive lock), however use FILE_USE_INCLUDE_PATH with caution. context A context resource. Simply set the flags parameter to LOCK_EX to obtain an exclusive lock during high concurrency. In addition, flock function also provides file locking method: <?php $fp = fopen("/tmp/lock.txt", "w+"); if (flock($fp, LOCK_EX)) { // 进行排它型锁定 fwrite($fp, "Write something here\n"); flock($fp, LOCK_UN); // 释放锁定 } else { echo "Couldn't lock the file !"; } fclose($fp); ?> Copy after login Note that flock() requires a file pointer. |