Master PHP’s fgetc(): Read Files & User Input Character by Character

This article explains how to use PHP's fgetc() function to read individual characters from files and standard input, covering opening files with fopen(), reading loops, handling end-of-file, and practical code examples for both file and user input scenarios.

php Courses
php Courses
php Courses
Master PHP’s fgetc(): Read Files & User Input Character by Character

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

Before using fgetc(), you must open the file with fopen(). Example:

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

After opening the file, you can read characters using fgetc() with the syntax fgetc($file). Example that reads the entire file character by character:

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

The while loop continues until fgetc() returns false, indicating the end of the file. fgetc() can also read a character from user input via STDIN. Example:

echo "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 summary, fgetc() is a PHP function for reading a single character from a file or from user input, and the examples above demonstrate its proper usage.

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.

file-handlingfgetcreading characters
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.