In PHP, fsync() forces the changes made to an open file to be written to the physical disk. It was added in PHP 8.1.
Normally the operating system keeps written data in memory for a short time. fsync() waits until the data and the file details are really stored, which protects you from losing them in a crash or power cut.
Syntax
Call fsync() with the values you need. Start with this line.
PHP
$ok = fsync($fp);
Call
What it does
fsync($fp)
Flushes the file data and details to disk and returns true on success.
fflush($fp); fsync($fp)
Empties PHP's own buffer first, then asks the system to save to disk.
@fsync($stream)
Hides the warning when the stream type does not support syncing.
fsync() needs PHP 8.1 or newer. It can be slow because it waits for the disk, so use it only for data you really cannot afford to lose, such as a payment log. For file content only, see fdatasync().
Library declarations
PHP
fsync(resource $stream): bool
Parameters
Parameter
Description
stream
Required. A file handle returned by fopen(). It must be a stream that supports syncing, such as a normal file.
Return Value
Return Value
Description
bool
Returns true on success or false on failure. It also returns false, with a warning, for streams that cannot be synced.
PHP Examples
Example 1 — Save Data Safely to Disk
Write a line, flush PHP's buffer, then ask the system to store it on disk.