What is the ftruncate() function in PHP?

ftruncate() is a built-in function in PHP.

The ftruncate() function truncates a file to the specified length.

If the specified length is greater than the size of the file, then the file is extended using null bytes.

The ftruncate() function

Syntax

The following is the function prototype:

ftruncate(file, size) 

Parameters and return value

The ftruncate() function takes the following input parameters:

  • file: The file to be truncated.

  • size: The new size of the file after truncation.

The function returns TRUE on success and FALSE on failure.

Code

main.php
Edpresso.txt
<?php
# Open file and read data
$file = fopen("Edpresso.txt", "a+");
while(!feof($file))
{
echo fgets($file);
}
# Print original file size
echo "\nFile size (before truncation): ", filesize("Edpresso.txt");
echo "\n";
# Truncate file to size 20 and close file
ftruncate($file, 20);
fclose($file);
# Re-open file and read data
$file = fopen("Edpresso.txt", "a+");
while(!feof($file))
{
echo fgets($file);
}
# Clear cache and print new size of file
clearstatcache();
echo "\nFile size (after truncation): ", filesize("Edpresso.txt");
fclose($file);
?>

In the above example, we start by printing the data in the file Edpresso.txt. The original size of the file is also printed (26).

Next, the ftruncate() function is invoked and the file is truncated to a length of 20. The file is closed and the cache is cleared.

The file is then re-opened and its data is printed. The new size of the file is also printed (20).

Notice how the ftruncate() function shortens the size of the file to 20 bytes. We can verify the new size by observing that when the data within the file is printed for the second time, the last 6 letters (u - z) are missing.

Free Resources

Copyright ©2026 Educative, Inc. All rights reserved