fgets() and fread() - What is the difference?

fread() for binary data and fread has a limit on how many chars you can read

$source_file = fopen( $filename, "r" ) or die("Couldn't open $filename");
while (!feof($source_file)) {
    $buffer = fread($source_file, 5);  
   var_dump($buffer); //return string with length 5 chars!
}

Number 5 is length bytes have been read .


fgets reads a line -- i.e. it will stop at a newline.

fread reads raw data -- it will stop after a specified (or default) number of bytes, independently of any newline that might or might not be present.


Speed is not a reason to use one over the other, as those two functions just don't do the same thing :

  • If you want to read a line, from a text file, then use fgets
  • If you want to read some data (not necessarily a line) from a file, then use fread.