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

mixed fgetc ( resource $handle )

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

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

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)

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

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

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.