January 22, 2021

WeAnswer

The complete guide to the beginners as well as to the experienced Web Developers

Difference between file, file_get_contents, and fopen in PHP

file

  •  Reads the entire file contents into an array of lines.

 

file_get_contents

  • Reads entire file contents into a string.
  • The file_ get_contents() the function gives good results until 40 MBytes and acceptable results until 100 MBytes but file_get_contents() loads the entire file into memory, so it’s not scalable.

fopen

  •  The fopen function does something entirely different—it opens a file descriptor, which functions as a stream to read or write the file. It is a much lower-level function, a simple wrapper around the C fopen function, and simply calling fopen won’t do anything but open a stream.

 


1.3 GB

Using fopen()

This process used 15555 ms for its computations.

It spent 169 ms in system calls.

Using file()

This process used 6983 ms for its computations.

It spent 4469 ms in system calls.

9.5 GB

Using fopen()

This process used 113559 ms for its computations.

It spent 2532 ms in system calls.

Using file()

This process used 8221 ms for its computations.

It spent 7998 ms in system calls.

Seems file() is faster.