Use ftruncate() when you need to changes the length of a file represented by an open writable stream in a PHP application. The examples below show the actual operation and its limitations.
What Is ftruncate() in PHP?
Changes the length of a file represented by an open writable stream. The exact signature supported by your installation depends on its PHP version and enabled extensions.
Its syntax is:
ftruncate($stream, int $size): 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,"ABCDEFG"); ftruncate($stream,3); rewind($stream); echo stream_get_contents($stream); fclose($stream);
Output:
ABC
Example 2: Different Input or Behavior
<?php
$stream = tmpfile(); fwrite($stream,"123456"); ftruncate($stream,0); echo fstat($stream)["size"]; fclose($stream);
Output:
0
Practical Example: Applying the Function
<?php
$stream = tmpfile(); fwrite($stream,"old content"); ftruncate($stream,0); rewind($stream); fwrite($stream,"new"); rewind($stream); echo stream_get_contents($stream); fclose($stream);
Output:
new
Important Behavior and Edge Cases
Truncation discards data permanently on real files; pointer position is not automatically reset.
Comparison With Related Functions
| Approach | Difference |
|---|---|
ftruncate() | Changes the length of a file represented by an open writable stream. |
| Related operation | fseek() changes position without changing file length; ftruncate() changes file length. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Ignoring the function-specific limitation | Truncation discards data permanently on real files; pointer position is not automatically reset. |
| Confusing this function with a related operation | fseek() changes position without changing file length; ftruncate() changes file length. |
Key Takeaways
- Changes the length of a file represented by an open writable stream.
- Truncation discards data permanently on real files; pointer position is not automatically reset.
- fseek() changes position without changing file length; ftruncate() changes file length.
Use ftruncate() for the specific operation demonstrated above. Check its prerequisites and handle failure conditions before using it with production data.