Created
September 7, 2012 06:37
-
-
Save microweber/3663864 to your computer and use it in GitHub Desktop.
PHp read large file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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