PHP fgets() Function
The PHP fgets() function returns a line from a given file pointer.
Syntax
fgets(stream, length)
Parameters
stream |
Required. Specify the file pointer to return a line from. It must be valid, and must point to a file successfully opened by fopen() or fsockopen(). |
length |
Optional. Specify maximum number of bytes to be read from a line. Reading ends when length - 1 bytes have been read, or a newline (which is included in the return value), or an EOF (whichever comes first). If not specified, it will keep reading from the stream until it reaches the end of the line. |
Return Value
Returns a string of up to length - 1 bytes read from the file pointed to by stream. If there is no more data to read in the file pointer, it returns false. If an error occurs, it returns false.
Example: Reading specified bytes from a file
Lets assume that we have a file called test.txt. This file contains following content:
This is a test file. It contains dummy content.
In the example below, the file is opened using fopen() function. Then the first 15 bytes from the first line is read. After performing this reading operation, it is closed using fclose() function.
<?php //open the file in read mode $fp = fopen("test.txt", "r") or die("Unable to open file!"); //reading first 15 bytes from the first //line and displaying the read content echo fgets($fp, 16); //close the file fclose($fp); ?>
The output of the above code will be:
This is a test
Example: Reading first line from a file
To read the first line from a file, the fgets() function can be used without length parameter. Consider the example below:
<?php //open the file in read mode $fp = fopen("test.txt", "r") or die("Unable to open file!"); //reading first line and //displaying the read content echo fgets($fp); //close the file fclose($fp); ?>
The output of the above code will be:
This is a test file.
Example: Reading a file line by line
By using feof() function in a while loop, a file can be read line by line. Consider the example below:
<?php //open the file in read mode $fp = fopen("test.txt", "r") or die("Unable to open file!"); //reading the file line by line //and displaying the read content while(!feof($fp)) { echo fgets($fp); } //close the file fclose($fp); ?>
The output of the above code will be:
This is a test file. It contains dummy content.
❮ PHP Filesystem Reference