Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way possible to read contents of a file

Tags:

php

file-io

Ok, I'm looking for the fastest possible way to read all of the contents of a file via php with a filepath on the server, also these files can be huge. So it's very important that it does a READ ONLY to it as fast as possible.

Is reading it line by line faster than reading the entire contents? Though, I remember reading up on this some, that reading the entire contents can produce errors for huge files. Is this true?

like image 363
SoLoGHoST Avatar asked May 01 '10 09:05

SoLoGHoST


1 Answers

If you want to load the full-content of a file to a PHP variable, the easiest (and, probably fastest) way would be file_get_contents.

But, if you are working with big files, loading the whole file into memory might not be such a good idea : you'll probably end up with a memory_limit error, as PHP will not allow your script to use more than (usually) a couple mega-bytes of memory.


So, even if it's not the fastest solution, reading the file line by line (fopen+fgets+fclose), and working with those lines on the fly, without loading the whole file into memory, might be necessary...

like image 58
Pascal MARTIN Avatar answered Sep 24 '22 15:09

Pascal MARTIN