What is fgetc in PHP?

PHP offers many functions for file manipulation. The fgetc function in PHP reads a single character from an already open file.

Syntax

The syntax for the `fgetc` function is shown below: ```perl fgetc(resource $file): string|false ```

Parameters

The `fgetc` function has one parameter: - `file`: This is a required parameter. `file` is the name of the file stream associated with the already opened file that we will read.

Return value

The `fgetc` function returns a single character read from the file. If it cannot return a character due to an error or by coming to the end of the file, `fgetc` will return `false`. > The `fgetc` function is not optimized for large files, as it only reads one character at a time.
The working of fgetc function.

Code

The following code shows how we can use the `fgetc` function in PHP.
main.php
test.txt
<?php
$file = fopen("test.txt","r"); // open the file
echo fgetc($file);
echo " ";
while(!feof($file)) //checks if at end of the file
{
echo fgetc($file); //reads one character from the file
}
fclose($file); // close the file
?>

Explanation

The file test.txt is opened and associated with the file pointer $file. A single call to the function returns a single character.

Subsequent calls to the function resume from the position of the last read character and, using this function in a loop, the entire file contents can be read character by character.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved