Current Location: Home> Latest Articles> PHP ftruncate() Function Explained: Truncate Files and Manage Size

PHP ftruncate() Function Explained: Truncate Files and Manage Size

M66 2025-07-12

PHP ftruncate() Function Explained

The ftruncate() function is used to truncate an already opened file to a specified length. In file operations, ftruncate() is a useful tool when you need to modify the size of a file. It returns TRUE on success and FALSE on failure.

Syntax

ftruncate(file_pointer, size);

Parameters

file_pointer - This is a file pointer that must be opened for writing. The file should be opened in a write mode to perform truncation.
size - This is the target size to which you want to truncate the file, specified in bytes.

Return Value

The ftruncate() function returns TRUE on success and FALSE on failure.

Example Code

<?php
    echo filesize("new.txt");
    echo " ";
    $file_pointer = fopen("new.txt", "a+");
    ftruncate($file_pointer, 50);
    fclose($file_pointer);
    clearstatcache();
    echo filesize("new.txt");
    fclose($file_pointer);
?>

Sample Output

400
50

Conclusion

This article covered the ftruncate() function in PHP, along with a practical example of how to use it. With this function, developers can easily truncate files and manage file sizes more flexibly in their applications.