What is the difference between readfile and file_get_contents?

7

In PHP, there are numerous ways to read the contents of a file.

The functions fopen , file , file_get_contents , readfile , and even a class named SplFileObject .

  • file reads line by line and puts them in array .
  • fopen reads the file and creates a resource to be manipulated with other functions such as fgets and fwrite .

  • SplFileObject is similar to fopen and related, however you have it all merged with the Iterators functionality.

But I'd like to know what the difference is between readfile and file_get_contents . For I know that the latter read the whole contents of the file, unlike the others.

But why then have both functions? Is there any difference between them?

    
asked by anonymous 04.05.2016 / 14:36

1 answer

5

file_get_contents() loads the entire file into memory, which can be a problem with large files. It is usually very useful when you need to treat the returned values of a file (for example, if you want to json_decode in a file that json you just opened).

readfile() does three things, reads the last file, writes the result directly to the buffer, and returns the function is the number of bytes in the file.

    
04.05.2016 / 14:51