note 36343 added to function.fopen

From: Date: Mon, 06 Oct 2003 16:44:01 +0000
Subject: note 36343 added to function.fopen
Groups: php.notes 
Request: Send a blank email to php-notes+get-57904@lists.php.net to get a copy of this message
a fast way of retrieving a single random line from a large file: <?php $fp = fopen("/path/to/file", "r"); $seek = rand(0, filesize("/path/to/file")); fseek($fp, $seek); fgets($fp); //set the filepointer to the beginning of the next line print fgets($fp); //fetch the actual line fclose ($fp); ?> ofcourse this can be easily used to retrieve more than one line quite easily. I've tried this on a 17mb irc log file on a p2 mmx 233 with 32MB ram and an old 1.2gb HD in a for-loop, running this section of code 100 times (including the fclose), an it finishes in an average of 0.5 seconds. The 800kb log file I tried did it in about 0.1 seconds. (note that there's a small chance, depending on your filesize, that the rand() will return the last byte and that the fgets will return EOF and nothing else, so you might want to use $seek = rand(1024, (filesize("path/to/file")) - 1024; instead so you should always get a valid line.) ---- Manual Page -- http://www.php.net/manual/en/function.fopen.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+36343 Delete -- http://master.php.net/manage/user-notes.php?action=delete+36343&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+36343&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#57904) next »