PHP - Remove last character of file

2020-03-12 03:47发布

问题:

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

回答1:

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



标签: php file-io trim