Backend Development 4 min read

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

This article explains how to use PHP's fgetc() function to read single characters from files and standard input, covering file opening with fopen(), the function's syntax, example code for looping through file contents, and a demonstration of handling user-entered characters with a switch statement.

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

PHP provides many file‑handling functions, and fgetc() is one that reads a single character from an opened file and moves the file pointer to the next character.

Before using fgetc() , you must open the file with fopen() . The following example shows how to open a file for reading:

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

After successfully opening the file, you can call fgetc() to read one character at a time. The syntax is simple:

fgetc($file)

Here $file is the resource pointer returned by fopen() . The following code reads the entire file character by character and echoes each character until the end of the file is reached:

$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 as long as fgetc() returns a character; when it returns false , the loop ends, indicating that all characters have been read.

In addition to reading from files, fgetc() can read a single character from user input via STDIN . The example below prompts the user, reads the input character, and uses a switch statement to respond accordingly:

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 demonstrates that fgetc() is useful both for file content processing and for interactive character input in PHP scripts.

backendPHPfile handlingfopenfgetcreading-input
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

login 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.