# fgets() and fread() - What is the difference in PHP?

PHPServer Side ProgrammingProgramming

The ‘fgets’ function reads a line and stops when it encounters a newline −

<?php
$file = fopen("test.txt","r"); echo fgets($file);
fclose($file); ?> The above code opens a text file named ‘test’ in the read mode and reads the contents of the file until a newline character is encountered beginning from the starting byte. The file is then closed. The ‘fread’ function reads raw data and stops after a specific number of bytes or default bytes. This doesn’t depend on whether a newline was encountered or not − <?php$file = fopen("test.txt","r");
fread($file,"10"); fclose($file);
?>

The above code opens a text file named ‘test’ in the read mode and reads 10 bytes after the starting byte. The file is then closed.

### When to use fgets and fread?

If the user wishes to read a line from a text file, it is suggested to use the ‘fgets’ function. On the other hand, if the user wishes to read some data (which need not be a line) from a file, then the ‘fread’ function can be used.

Published on 07-Apr-2020 13:01:22