foreline
foreline

Reputation: 3821

PHP: How to delete last N bytes from large file?

I have a large file and need to delete last 512 bytes. I don't want to duplicate file.

Thanks.

Upvotes: 3

Views: 1674

Answers (3)

Francesco Casula
Francesco Casula

Reputation: 27130

Usage example with fstat, ftruncate, fopen and fclose:

<?php    

$bytesToTruncate = 5; // how many bytes we are going to delete from the end of the file

$handle = fopen('/home/francesco/mytest', 'r+'); // Open for reading and writing; place the file pointer at the beginning of the file.

$stat = fstat($handle);
$size = $stat['size'] - $bytesToTruncate;
$size = $size < 0 ? 0 : $size;

ftruncate($handle, $size);
fclose($handle);

Upvotes: 3

zeuxcg
zeuxcg

Reputation: 9404

You should use ftruncate(handle, file_size - 512) (get the file size with filesize or fstat function)

Upvotes: 10

&#193;lvaro Gonz&#225;lez
&#193;lvaro Gonz&#225;lez

Reputation: 146460

I haven't tested it with large files but you can give it a try:

Upvotes: 2

Related Questions