0 0 Votes

PHP: Difference between fgets and fread?

Question by Compi | 13/06/2013 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?

ReplyPositiveNegative

Computer Expert

Show Profile | Message
Avatar
0Best Answer
0 Votes

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.
15/06/2013 at 17:16

ReplyPositive Negative
Reply

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.

Participate

Ask your own question or write your own articles on askingbox.com. How to do.