In PHP, ftruncate() cuts an open file down to a given size, or makes it larger by adding empty bytes. It is the quick way to empty a file or trim off the end.
The file must be opened with a mode that allows writing, such as r+ or w. The function changes only the file size and does not move the file pointer.
Syntax
Call ftruncate() with the values you need. Start with this line.
PHP
$ok = ftruncate($fp, 5);
Call
What it does
ftruncate($fp, 0)
Empties the file completely.
ftruncate($fp, 5)
Keeps only the first 5 bytes of the file.
ftruncate($fp, 100)
Makes the file 100 bytes long, filling any new space with null bytes.
After ftruncate($fp, 0) the pointer still sits at its old position. Call rewind($fp) before writing again, or PHP will pad the start of the file with null bytes.
Library declarations
PHP
ftruncate(resource $stream, int $size): bool
Parameters
Parameter
Description
stream
Required. A file handle opened with a write mode such as r+, w or a+. A handle opened with r cannot be truncated.
size
Required. The new size of the file in bytes. It must be 0 or greater.
Return Value
Return Value
Description
bool
Returns true on success or false on failure, for example when the file was opened read only.
PHP Examples
Example 1 — Cut a File Down to 5 Bytes
Open a file for reading and writing, then keep only its first 5 bytes.