The ftruncate Function
The ftruncate
function truncates a file to the specified size. The first parameter of the function is a file handle, and the second is the size to which the file should be truncated. If the file was larger than the specified size, the extra data will be lost. If the file was smaller, it will be padded with null bytes.
Syntax
ftruncate(resource $handle, int $size): bool
Example
Truncate a file to 100 bytes:
<?php
$file = fopen('example.txt', 'r+');
ftruncate($file, 100);
fclose($file);
?>
The function will return true on success or false on error.
Example
Create an empty file of a given size:
<?php
$file = fopen('empty.dat', 'w');
ftruncate($file, 1024); // create a 1 KB file
fclose($file);
?>
Example
Checking the result of the function execution:
<?php
$file = fopen('test.txt', 'r+');
$res = ftruncate($file, 50);
if ($res) {
echo 'file truncated successfully';
} else {
echo 'error truncating file';
}
fclose($file);
?>