Home  >  Article  >  Backend Development  >  file_put_contents high concurrency and exclusive locking issues

file_put_contents high concurrency and exclusive locking issues

WBOY
WBOYOriginal
2016-07-25 08:56:301940browse
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);
?>

Note that flock() requires a file pointer.



Statement:
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