PHP: How to remove the last N bytes from a large file?

I have a large file and you need to delete the last 512 bytes. I do not want to duplicate the file.

Thank.

+3
source share
3 answers

You should use ftruncate(handle, file_size - 512)(get file size using function filesizeor fstat)

+10
source

I have not tested it with large files, but you can try:

+2
source

fstat, ftruncate, fopen 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);
+2

Source: https://habr.com/ru/post/1782688/


All Articles