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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With