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