11 Vote

PHP: Difference between fgets and fread

Question by Compi | Last update on 2021-04-06 | Created on 2013-06-13

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 what is the exact difference?

ReplyPositiveNegative
2Best Answer2 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 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
Reply

Related Topics

PHP: Current Date and Time

Tutorial | 0 Comments

PHP: Sending an E-Mail

Tutorial | 0 Comments

PHP: Upload of large Files

Tutorial | 0 Comments

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 article on askingbox.com. That’s how it’s done.