Backend Development 4 min read

Using PHP fgetc() to Read Characters from a File

This article explains the PHP fgetc() function, its syntax, parameters, return values, important usage notes, and provides a complete code example demonstrating how to open a file, read characters one by one, and properly close the file, along with alternatives for reading larger data.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP fgetc() to Read Characters from a File

Syntax

<code>mixed fgetc ( resource $handle )</code>

Parameter Description

handle : required. File pointer resource specifying the file to read.

Return Value

If successful, returns the read character; if the end of file is reached, returns FALSE .

Notes

Before calling fgetc() , you must open the file with fopen() and pass the returned handle to fgetc() . After reading all characters, close the file with fclose() .

Usage Example

<code>$handle = fopen("file.txt", "r"); // open file
if ($handle) {
    while (($char = fgetc($handle)) !== false) { // read each character
        echo $char;
    }
    fclose($handle); // close file
}
</code>

In this example, fopen() opens "file.txt" and returns a file handle stored in $handle . A while loop with fgetc() reads characters one by one until false indicates EOF, and fclose() closes the file.

Note that fgetc() reads only a single character at a time; to read an entire line or the whole file you can use fgets() or file_get_contents() .

Summary

fgetc() is a PHP function for reading a single character from a file. It requires the file to be opened with fopen() and closed with fclose() . For larger reads, consider using fgets() or file_get_contents() .

Recommended PHP Learning Resources

Vue3+Laravel8+Uniapp Beginner to Advanced Development Tutorial

Vue3+TP6+API Social E‑commerce System Development Course

Swoole From Beginner to Master Course

Workerman+TP6 Real‑time Chat System (Limited Offer)

BackendPHPfile handlingphp-functionsfgetc
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.