note 42381 added to function.fread

From: Date: Fri, 14 May 2004 04:32:51 +0000
Subject: note 42381 added to function.fread
Groups: php.notes 
Request: Send a blank email to php-notes+get-69593@lists.php.net to get a copy of this message
The following function retrieves a line in a file, regardless of its size, so you won't get an error if the file's size is beyond php's allowed memory limit (the string has to be below however), which is something i was needing for accessing a big log file generated by a webhost. Indexes start at 1 (so $line = 1 means the first line unlike arrays). If the file is small, it would be better to use "file()" however. function strpos_count($haystack, $needle, $i = 0) { while (strpos($haystack,$needle) !== false) {$haystack = substr($haystack, (strpos($haystack,$needle) + 1)); $i++;} return $i; } function getLine($file,$line=1){ $occurence = 0; $contents = ''; $startPos = -1; if (!file_exists($file)) return ''; $fp = @fopen($file, "rb"); if (!$fp) return ''; while (!@feof($fp)) { $str = @fread($fp, 1024); $number_of_occurences = strpos_count($str,"\n"); if ($number_of_occurences == 0) {if ($start_pos != -1) {$contents .= $str;}} else { $lastPos = 0; for ($i = 0; $i < $number_of_occurences; $i++){ $pos = strpos($str,"\n", $lastPos); $occurence++; if ($occurence == $line) { $startPos = $pos; if ($i == $number_of_occurences - 1) {$contents = substr($str, $startPos + 1);} } elseif ($occurence == $line + 1) { if ($i == 0) {$contents .= substr($str, 0, $pos);} else {$contents = substr($str, $startPos, $pos - $startPos);} $occurence = 0; break; } $lastPos = $pos + 1; } } } @fclose($fp); return $contents; } ---- Manual Page -- http://www.php.net/manual/en/function.fread.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+42381 Delete -- http://master.php.net/manage/user-notes.php?action=delete+42381&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+42381&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#69593) next »