The fgets() function in PHP is an inbuilt function which is used to return a line from an open file.
- It is used to return a line from a file pointer and it stops returning at a specified length, on end of file(EOF) or on a new line, whichever comes first.
- The file to be read and the number of bytes to be read are sent as parameters to the fgets() function and it returns a string of length -1 bytes from the file pointed by the user.
- It returns False on failure.
fgets(file, length) Parameters Used: The fgets() function in PHP accepts two parameters. file : It specifies the file from which characters have to be extracted. length : It specifies the number of bytes to be read by the fgets() function. The default value is 1024 bytes.
Return Value : It returns a string of length -1 bytes from the file pointed by the user or False on failure.
Errors And Exceptions
- The function is not optimised for large files since it reads a single line at a time and it may take a lot of time to completely read a long file.
- The buffer must be cleared if the fgets() function is used multiple times.
- The fgets() function returns Boolean False but many times it happens that it returns a non-Boolean value which evaluates to False.
Suppose there is a file named “gfg.txt” which consists of :
This is the first line.
This is the second line.
This is the third line.
This is the first line.
This is the first line. This is the second line. This is the third line.
- PHP | SplFileObject fgets() Function
- How to get the function name inside a function in PHP ?
- PHP | Ds\Set first() Function
- D3.js | d3.set.has() Function
- p5.js | arc() Function
- PHP | next() Function
- PHP | Ds\Map xor() Function
- PHP | Ds\Set contains() Function
- PHP | dir() Function
- PHP | Ds\Set last() Function
- PHP | exp() Function
- PHP | each() Function
- PHP | Ds\Map map() Function
- PHP | Ds\Map last() Function
- p5.js | nfp() Function
- p5.js | nfs() Function
- PHP | pow( ) Function
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.