Skip to content

Instantly share code, notes, and snippets.

@mamchenkov
Last active December 19, 2015 21:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mamchenkov/6022397 to your computer and use it in GitHub Desktop.
Save mamchenkov/6022397 to your computer and use it in GitHub Desktop.
Read file line-by-line from given byte offset. Handy for re-processing large logs files.
<?php
/**
* Read file line-by-line from given byte offset.
* Handy for re-processing large logs files.
*/
// Filename to use for temporary data
define('DATA_FILE', 'data.log');
// Create the data file on the fly
$data = <<<EOF
one
line two
line three
another line number four
five
six six six
seven eleven
EOF;
if (!file_put_contents(DATA_FILE, $data)) {
print "Failed to write sample data to file\n";
exit(1);
}
// Open file
$fh = fopen(DATA_FILE, 'r');
if (!$fh) {
print "Failed to open file for reading\n";
exit(1);
}
// Move to specified position, or stay on top
$from = empty($argv[1]) ? 0 : $argv[1];
fseek($fh, $from);
// Read line-by-line from given position
while (($line = fgets($fh)) !== false) {
$line = trim($line);
$pos = ftell($fh);
$pos = $pos - strlen($line) - 1; // 1 is for line break
print "Position: $pos, Line: $line\n";
}
fclose($fh);
// Remove data file
unlink(DATA_FILE);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment