Using PHP fgetc() to Read 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 character-by-character reading using a while loop, and provides a user input handling example with a switch statement.
In PHP, the fgetc() function reads a single character from an opened file and moves the file pointer to the next character.
Before using fgetc() , a file must be opened with fopen() . Example:
<code>$file = fopen("example.txt", "r");
if ($file) {
// file opened successfully
// other file operations
} else {
echo "Unable to open file!";
}
</code>The syntax of fgetc() is simply fgetc($file) , where $file is the file resource.
To read an entire file character by character, a while loop can be used:
<code>$file = fopen("example.txt", "r");
if ($file) {
while (($char = fgetc($file)) !== false) {
echo $char;
}
fclose($file);
} else {
echo "Unable to open file!";
}
</code>The loop continues until fgetc() returns false , indicating end‑of‑file.
fgetc() can also read a single character from standard input. The following example prompts the user and processes the input with a switch statement:
<code>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";
}
</code>By understanding and applying fgetc() , developers can perform fine‑grained file reading and interactive character input in PHP backend applications.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.