Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between file, file_get_contents, and fopen in PHP

Tags:

file

php

fopen

I am new to PHP, and I am not quite sure: what is the difference between the file(), file_get_contents(), and fopen() functions, and when should I use one over the other?

like image 479
c00L Avatar asked Jun 03 '14 05:06

c00L


People also ask

What is the difference between file_get_contents () function and file () function?

The file_get_contents() function reads entire file into a string. The file() function reads the entire file in a array, whereas file_get_contents() function reads the entire file into a string.

What is the difference between the file () and file_get_contents () functions write with small program?

Difference between file_get_contents() and file_put_contents() Functions: The main difference between file_get_contents() and file_put_contents() functions is that file_get_contents() function reads a file into a string and file_put_contents() function writes a string to a file. 1.

What is the use of file_get_contents in PHP?

The file_get_contents() reads a file into a string. This function is the preferred way to read the contents of a file into a string. It will use memory mapping techniques, if this is supported by the server, to enhance performance.


2 Answers

The first two, file and file_get_contents are very similar. They both read an entire file, but file reads the file into an array, while file_get_contents reads it into a string. The array returned by file will 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 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.

Once you've open a handle to the file, you can use other functions like fread and fwrite to manipulate the data the handle refers to, and once you're done, you will need to close the stream by using fclose. 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.
like image 119
Alexis King Avatar answered Oct 04 '22 06:10

Alexis King


file — Reads entire file into an array
file_get_contents — Reads entire file into a string
fopen — Opens file or URL

like image 25
Miraage Avatar answered Oct 04 '22 05:10

Miraage