Use fsync() when you need to requests synchronization of stream data and metadata to storage in a PHP application. The examples below show the actual operation and its limitations.
What Is fsync() in PHP?
Requests synchronization of stream data and metadata to storage. The exact signature supported by your installation depends on its PHP version and enabled extensions.
Its syntax is:
fsync($stream): bool
Parameters and return value: The parameter types, optional arguments, references, and return type are shown in the signature above. Optional parameters are marked with an ellipsis in this reference signature.
Example 1: Basic Usage
<?php
$stream = tmpfile(); fwrite($stream,"Record"); var_dump(fsync($stream)); fclose($stream);
Output:
bool(true)
Example 2: Different Input or Behavior
<?php
$stream = tmpfile(); fwrite($stream,"Saved
"); fflush($stream); echo fsync($stream) ? "Synchronized" : "Failed"; fclose($stream);
Output:
Synchronized
Practical Example: Applying the Function
<?php
$stream = tmpfile(); $written = fwrite($stream,"Transaction log
"); if ($written !== false && fsync($stream)) echo "Sync requested"; fclose($stream);
Output:
Sync requested
Important Behavior and Edge Cases
Successful synchronization is not a substitute for transactional storage or a durable backup.
Comparison With Related Functions
| Approach | Difference |
|---|---|
fsync() | Requests synchronization of stream data and metadata to storage. |
| Related operation | fdatasync() focuses on data and necessary metadata; fsync() also syncs metadata. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Ignoring the function-specific limitation | Successful synchronization is not a substitute for transactional storage or a durable backup. |
| Confusing this function with a related operation | fdatasync() focuses on data and necessary metadata; fsync() also syncs metadata. |
Key Takeaways
- Requests synchronization of stream data and metadata to storage.
- Successful synchronization is not a substitute for transactional storage or a durable backup.
- fdatasync() focuses on data and necessary metadata; fsync() also syncs metadata.
Use fsync() for the specific operation demonstrated above. Check its prerequisites and handle failure conditions before using it with production data.