PHP Function Reference

PHP ftruncate() Function



The PHP ftruncate() function truncates an open file to the specified length.

Syntax

ftruncate(stream, length)

Parameters

stream Required. Specify the file pointer to truncate. The stream must be open for writing.
length Required. Specify the size to truncate to. If size is larger than the file then the file is extended with null bytes. If size is smaller than the file then the file is truncated to that size.

Return Value

Returns true on success or false on failure.

Example:

Lets assume that we have a file called test.txt. This file contains following content:

This is a test file.
It contains dummy content.

In the example below, the content of the file is displayed before and after truncating its content.

<?php
//content of the file before truncation
echo file_get_contents("test.txt");

//truncating the file to 15 bytes
$fp = fopen("test.txt", "r+");
ftruncate($fp, 15);
fclose($fp);

//content of the file after truncation
echo "\n\n".file_get_contents("test.txt");
?>

The output of the above code will be:

This is a test file.
It contains dummy content.

This is a test 

❮ PHP Filesystem Reference