What is the difference between readfile and file_get_contents?

Asked

Viewed 885 times

7

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

There are the functions fopen, file, file_get_contents, readfile, and even a class called SplFileObject.

  • file reads line by line and puts them in a 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, but you have all this merged with the functionality of Iterators.

But I’d like to know the difference between readfile and file_get_contents. For I know that the latter read all the contents of the archive, unlike the others.

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

1 answer

5


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

readfile() does three things, reads the file passed, writes the result directly into the buffer and the return of the function is the number of bytes of the file.

  • This last byte number information I didn’t know +1

  • I upgraded it there for the file_get_contents, because if it doesn’t look like he "is bad" and that readfile "it’s good".

  • @Wallacemaxters wouldn’t be json_encode()? Decode vc generally stores, the Encode usually does not. ex: $json = json_encode($str); echo $json;, flipped readfile(json_encode($str)) that would be it?

  • No, I mean if you want to decode a file json

  • For example, it is useful to open the composer.json and turn it into a array in Php :)

  • @Wallacemaxters now I understand, haha I’m with the readfile() in the xD head if it was to make a fopen()/fgets() in place file_get_contetns() to decode the json was to chip.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.