Skip to content

Instantly share code, notes, and snippets.

@microweber
Created September 7, 2012 06:37
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 microweber/3663864 to your computer and use it in GitHub Desktop.
Save microweber/3663864 to your computer and use it in GitHub Desktop.
PHp read large file
/**
* Demonstrate an efficient way to search the last 100 lines of a file
* containing roughly ten million lines for a sample string. This should
* function without having to process each line of the file (and without making
* use of the “tail” command or any external system commands).
*/
$filename = '/opt/local/apache2/logs/karwin-access_log';
$searchString = 'index.php';
$numLines = 100;
$maxLineLength = 200;
$fp = fopen($filename, 'r');
$data = fseek($fp, -($numLines * $maxLineLength), SEEK_END);
$lines = array();
while (!feof($fp)) {
$lines[] = fgets($fp);
}
$c = count($lines);
$i = $c >= $numLines? $c-$numLines: 0;
for (; $i<$c; ++$i) {
if ($pos = strpos($lines[$i], $searchString)) {
echo $lines[$i];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment