Backend Development 4 min read

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

This article explains the PHP fgetc() function for reading a single character from an opened file or user input, demonstrates how to open files with fopen(), shows example code for reading characters in a loop, and provides usage tips for file handling and interactive input.

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

In PHP there are many file‑handling functions, and one of them is fgetc() , which reads a single character from an opened file and moves the file pointer forward.

Before using fgetc() you must open a file, typically 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 {
    echo "Unable to open file!";
}

After the file is successfully opened, you can call fgetc($file) to read one character. The syntax is simply:

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:

$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 characters from standard input. The example below prompts the user for a character, reads it with fgetc(STDIN) , and uses a switch statement to react to the input:

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. The examples above demonstrate proper usage and help readers understand how to perform file operations and interactive character input in PHP.

The article also provides links to download learning materials for Java, C, C++, frontend development, and PHP.

PHPfile handlingfopencharacter inputfgetc
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.