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

This article explains the PHP fgetc() function, shows how to open files with fopen(), demonstrates reading characters from files and standard input using loops and switch statements, and provides complete code examples for practical use.

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

In PHP, the fgetc() function reads a single character from an opened 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
    // other file operations
} else {
    echo "Unable to open file!";
}

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

Reading the entire file character by character can be done with a while loop:

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

The same function can also read a character from standard input. 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 summary, fgetc() is a PHP function for reading a single character from a file or from user input, and the examples above demonstrate its correct 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.

BackendPHPCode Examplefile-handlingfgetc
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.