Using PHP fgetc() to Read Characters from Files and Standard Input

This article explains PHP's fgetc() function for reading a single character from an opened file or standard input, demonstrates how to open files with fopen(), shows example code for character-by-character reading using a while loop, and provides a user input handling example with a switch statement.

php Courses
php Courses
php Courses
Using PHP fgetc() to Read Characters from Files and Standard Input

In PHP, the fgetc() function reads a single character from an opened file and moves the file pointer to the next character.

Before using fgetc(), a file must be opened with fopen(). Example:

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

The syntax of fgetc() is simply fgetc($file), where $file is the file resource.

To read an entire file character by character, a while loop can be used:

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

The loop continues until fgetc() returns false, indicating end‑of‑file. fgetc() can also read a single character from standard input. The following example prompts the user and processes the input with a switch statement:

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";
}

By understanding and applying fgetc(), developers can perform fine‑grained file reading and interactive character input in PHP backend applications.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Backendreadinginputfile-handlingfopenfgetc
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.