What's the difference between fopen('file.txt', 'r') and file('file.txt')? They both appear to be the same...
- 9,685
- 10
- 45
- 77
-
to add to the confusion, there's also file_get_contents() and file_put_contents() to read or write a whole file – Ivo P Jul 13 '17 at 07:56
-
How so? All these functions have documentations explaining what they do. Just because the final result might be the same in some situations doesn't mean the functions are the same. – Yoshi Jul 13 '17 at 07:57
-
It was a good question. Too bad it's been asked before (and a lot). – apokryfos Jul 13 '17 at 08:07
-
[`fopen()`](http://php.net/manual/en/function.fopen.php) and [`file()`](http://php.net/manual/en/function.file.php) being the same? Where did you learn PHP from? Drop that tutorial and get your information from the [official documentation](http://php.net/manual/). – axiac Jul 13 '17 at 08:37
1 Answers
Here's some info. Quote on file(), file_get_contents(), and fopen():
The first two,
fileandfile_get_contentsare very similar. They both read an entire file, butfilereads the file into an array, whilefile_get_contentsreads it into a string. The array returned byfilewill be separated by newline, but each element will still have the terminating newline attached, so you will still need to watch out for that.The
fopenfunction 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 Cfopenfunction, and simply callingfopenwon't do anything but open a stream.Once you've open a handle to the file, you can use other functions like
freadandfwriteto manipulate the data the handle refers to, and once you're done, you will need to close the stream by usingfclose. These give you much finer control over the file you are reading, and if you need raw binary data, you may need to use them, but usually you can stick with the higher-level functions.So, to recap:
file— Reads entire file contents into an array of lines.file_get_contents— Reads entire file contents into a string.fopen— Opens a file handle that can be manipulated with other library functions, but does no reading or writing itself.
Credit goes to Alexis King.
- 1,134
- 1
- 15
- 32