Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Remove last character of file

Tags:

php

file-io

trim

I have a little php script that removes the last character of a file.

$contents = file_get_contents($path);
rtrim($contents);
$contents = substr($contents, 0, -1);
$fh = fopen($path, 'w') or die("can't open file");
fwrite($fh, $contents);
fclose($fh);    

So it reads in the file contents, strips off the last character and then truncates the file and writes the string back to it. This all works fine.

My worry is that this file could contain a lot of data and the file_get_contents() call would then hold all this data in memory which could potentially max out my servers memory.

Is there a more efficient way to strip the last character from a file?

Thanks

like image 523
sulman Avatar asked Dec 02 '11 09:12

sulman


1 Answers

Try this

$fh = fopen($path, 'r+') or die("can't open file");

$stat = fstat($fh);
ftruncate($fh, $stat['size']-1);
fclose($fh); 

For more help see this

like image 186
azat Avatar answered Nov 04 '22 10:11

azat