Current Location: Home> Latest Articles> PHP fgetc() Function Explained: How to Read a Single Character from a File

PHP fgetc() Function Explained: How to Read a Single Character from a File

M66 2025-10-15

Introduction to PHP fgetc() Function

In PHP, file operations are a common part of development, and the fgetc() function is one of the most useful tools for reading files character by character. It allows developers to process file content precisely and even handle single-character user input.

What Does fgetc() Do?

The fgetc() function reads one character from an open file and automatically moves the file pointer to the next character. Each time it’s called, it returns the current character until it reaches the end of the file, where it returns false.

Opening a File Before Using fgetc()

Before using fgetc(), you must open a file with the fopen() function. Here’s an example:

$file = fopen("example.txt", "r");
if ($file) {
    // File opened successfully
} else {
    echo "Unable to open the file!";
}

In this example, the file is opened in read-only mode (r) using fopen().

Syntax of fgetc()

fgetc($file)

Here, $file represents the file resource obtained from fopen().

Example: Reading a File with fgetc()

The following example demonstrates how to use fgetc() to read each character from a file and output it:

$file = fopen("example.txt", "r");
if ($file) {
    while (($char = fgetc($file)) !== false) {
        echo $char;
    }
    fclose($file);
} else {
    echo "Unable to open the file!";
}

In this code, a while loop repeatedly calls fgetc() to retrieve each character until it returns false, indicating the end of the file.

Example: Reading User Input with fgetc()

Besides reading from files, fgetc() can also be used to read a single character from user input. For example:

echo "Please enter a character: ";
$input = fgetc(STDIN);

switch ($input) {
    case 'a':
        echo "You entered the letter a";
        break;
    case 'b':
        echo "You entered the letter b";
        break;
    case 'c':
        echo "You entered the letter c";
        break;
    default:
        echo "Invalid character entered";
}

In this example, fgetc(STDIN) reads a single character from the standard input stream, and a switch statement is used to perform actions based on the entered character.

Conclusion

The fgetc() function is a simple yet powerful tool for file handling in PHP. It can be used to read file content character by character or to handle single-character user input. Mastering fgetc() enables developers to work more effectively with files and interactive input in PHP applications.