PHP fgetc() Function
The PHP fgetc() function returns a character from the given file pointer.
Note: This function is binary-safe.
Syntax
fgetc(stream)
Parameters
stream |
Required. Specify the file pointer to return a character from. It must be valid, and must point to a file successfully opened by fopen() or fsockopen(). |
Return Value
Returns a string containing a single character read from the file pointed to by stream. Returns false on EOF.
Note: This function may return Boolean false, but may also return a non-Boolean value which evaluates to false. Therefore, use === operator for testing the return value of this function.
Example: Reading first character 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 character 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 character from the first //line and displaying the read content echo fgetc($fp); //close the file fclose($fp); ?>
The output of the above code will be:
T
Example: Reading whole file
By using feof() function in a while loop, a file can be read character by character. 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 character by character //and displaying the read content while(!feof($fp)) { echo fgetc($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