Asked 6 years ago
24 Apr 2017
Views 2614
sachin

sachin posted

how to read file in chunk in PHP ?

dealing with very large data file and want to read without memory crash .


$handle=fopen($filename,"r");
$contents = fread($handle, filesize($filename));
fclose($handle);


fread will read all content file which is time consuming and some time script goes out of order

so is there any way we can read data in chunk with good library or something ?

so file read in PHP so no memory issue and fast processing for large file


python

python
answered Jun 25 '22 00:00

use fgets() function to read the file, it helps read the file in a chunk in PHP
how fgets() help read files in chunks in PHP?
because fgets() read one line at a time so in other words, it will read in chunks,
if it failed to read one line as well than you can size of max content fgets should read at a time
example:

 $filepointer = fopen("bigfile.mov", "r");
if ($filepointer) {
    while (($content = fgets($filepointer, 1024)) !== false) {
        echo $content;
    }
     fclose($filepointer);
}
 

in above example, fgets read a line or 1023 bytes () which over shorter

Rasi

Rasi
answered Nov 30 '-1 00:00

smartReadFile is good lib for reading file through PHP controller



require_once('smartReadFile.php');
smartReadFile($path, $filename, $type);

Post Answer