Skip to Content
PHP Cookbook
book

PHP Cookbook

by David Sklar, Adam Trachtenberg
November 2002
Intermediate to advanced
640 pages
16h 33m
English
O'Reilly Media, Inc.
Content preview from PHP Cookbook

18.15. Removing the Last Line of a File

Problem

You want to remove the last line of a file; for example, someone’s added a comment to the end of your guestbook. You don’t like it, so you want to get rid of it.

Solution

If the file is small, you can read it into an array with file( ) and then remove the last element of the array:

$lines = file('employees.txt');
array_pop($lines);
$file = join('',$lines);

Discussion

If the file is large, reading it into an array requires too much memory. Instead, use this code, which seeks to the end of the file and works backwards, stopping when it finds a newline:

$fh = fopen('employees.txt','r') or die("can't open: $php_errormsg"); $linebreak = $beginning_of_file = 0; $gap = 80; $filesize = filesize('employees.txt'); fseek($fh,0,SEEK_END); while (! ($linebreak || $beginning_of_file)) { // save where we are in the file $pos = ftell($fh); /* move back $gap chars, use rewind() to go to the beginning if * we're less than $gap characters into the file */ if ($pos < $gap) { rewind($fh); } else { fseek($fh,-$gap,SEEK_CUR); } // read the $gap chars we just seeked back over $s = fread($fh,$gap) or die($php_errormsg); /* if we read to the end of the file, remove the last character * since if it's a newline, we should ignore it */ if ($pos + $gap >= $filesize) { $s = substr_replace($s,'',-1); } // move back to where we were before we read $gap chars into $s if ($pos < $gap) { rewind($fh); } else { fseek($fh,-$gap,SEEK_CUR); } // is there a linebreak in ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
PHP Cookbook, 2nd Edition

PHP Cookbook, 2nd Edition

Adam Trachtenberg, David Sklar
PHP Cookbook, 3rd Edition

PHP Cookbook, 3rd Edition

David Sklar, Adam Trachtenberg
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe

Publisher Resources

ISBN: 1565926811Supplemental ContentCatalog PageErrata