PHP fgetc() Function: Reading 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 looping through file contents, and provides a user input example with a switch statement.

php Courses
php Courses
php Courses
PHP fgetc() Function: Reading Characters from Files and Standard Input

In PHP, the fgetc() function reads a single character from an open file and advances the file pointer.

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

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

After opening the file, fgetc($file) reads one character. Its syntax is: fgetc($file) The variable $file is a resource pointer to the opened file. The following example reads the entire file character by character and outputs each character:

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

The loop uses while to read each character until fgetc() returns false, indicating end of file.

Besides file reading, fgetc() can read a character from user input via STDIN. 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";
}

This script prompts the user, captures a single character, and uses a switch statement to respond accordingly.

In summary, the fgetc() function is a PHP built‑in for reading a single character from a file or from standard input, and the examples above demonstrate its correct usage for file operations and interactive input.

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.

BackendPHPTutorialfile-handlingfgetcstdin
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.