00 Votes

PHP: Difference between fgets and fread?

Question by Compi | 2013-06-13 at 19:15

I would like to read a file using PHP. When searching for scripts on the web, I have seen different solutions. Some are using fgets(), others are using fread().

But I did not got the difference between these two functions. Is one of them faster? When should I use which function and where is the exact difference?

1Best Answer1 Vote

When to use which of these functions depends on what you would like to do:

  • The function fgets reads a single line from a text file. It is reading so long until the end of the current line (or the end of the file) is reached. Therefore, if you would like to read one line from a text file, you should use fgets.
  • The function fread not only reads until the end of the line but to the end of the file [e.g. fread($handle)] or as many bytes as specified as a parameter [e.g. fread($handle, 1024)]. So, if you would like to read a complete file, no matter whether it is a text file with all containing lines or arbitrary raw data from a file, you should use fread.

By the way, the speed of the two functions is negligible, both of them have the same speed. When making a choice, it is only important to decide, whether you want to read line by line or not.
2013-06-15 at 17:16

ReplyPositive Negative

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.


Ask your own question or write your own article on askingbox.com. That’s how it’s done.