
- PHP 7 Tutorial
- PHP 7 - Home
- PHP 7 - Introduction
- PHP 7 - Performance
- PHP 7 - Environment Setup
- PHP 7 - Scalar Type Declarations
- PHP 7 - Return Type Declarations
- PHP 7 - Null Coalescing Operator
- PHP 7 - Spaceship Operator
- PHP 7 - Constant Arrays
- PHP 7 - Anonymous Classes
- PHP 7 - Closure::call()
- PHP 7 - Filtered unserialize()
- PHP 7 - IntlChar
- PHP 7 - CSPRNG
- PHP 7 - Expectations
- PHP 7 - use Statement
- PHP 7 - Error Handling
- PHP 7 - Integer Division
- PHP 7 - Session Options
- PHP 7 - Deprecated Features
- PHP 7 - Removed Extensions & SAPIs
- PHP 7 Useful Resources
- PHP 7 - Quick Guide
- PHP 7 - Useful Resources
- PHP 7 - Discussion
fgets() and fread() - What is the difference in PHP?
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.
- Related Articles
- fgets() function in PHP
- fread() function in PHP
- fgets() and gets() in C
- What is the difference between echo, print, and print_r in PHP?
- What is the difference between array_merge and array + array in PHP?
- fread() function in C++
- Explain the functions fread() and fwrite() used in files in C
- fread() function in C++ program
- What is the difference between 'isset()' and '!empty()' in PHP?
- Difference between the AND and && operator in php
- Difference between the and$ operator in php
- Difference between the | and || or operator in php
- Difference between gettype() in PHP and get_debug_type() in PHP 8
- How to save a csv and read using fread in R?
- Difference between !== and ==! operator in PHP
