Content · Programming · PHP

PHP fgetc() Function: Usage and Examples

Learn how PHP fgetc works with practical examples, important behavior, relevant alternatives and common mistakes.

1 views Published Oct 16, 2026 Updated Oct 16, 2026

Reads a single byte from a file stream.

What Is fgetc() in PHP?

Reads a single byte from a file stream.

Its syntax is:

fgetc(resource $stream): string|false

Parameters:

  • $stream — Accepted as resource; required argument.

Return type: string|false. Reads bytes rather than UTF-8 characters. Test strictly against false to distinguish EOF from the string "0".

Availability: Requires an open readable stream.

Example 1: Basic Usage

<?php

$stream = fopen("php://memory", "r+"); fwrite($stream, "AB"); rewind($stream); echo fgetc($stream); fclose($stream);

Output:

A

Reads bytes rather than UTF-8 characters. Test strictly against false to distinguish EOF from the string "0".

Example 2: A Different Input

<?php

$stream = fopen("php://memory", "r+"); fwrite($stream, "Z"); rewind($stream); fgetc($stream); var_dump(fgetc($stream)); fclose($stream);

Output:

bool(false)

Reads bytes rather than UTF-8 characters. Test strictly against false to distinguish EOF from the string "0".

Practical Example: Applying It in a Program

<?php

$stream = fopen("php://memory", "r+"); fwrite($stream, "ABC"); rewind($stream); while (($character = fgetc($stream)) !== false) { echo "[" . $character . "]"; } fclose($stream);

Output:

[A][B][C]

Reads bytes rather than UTF-8 characters. Test strictly against false to distinguish EOF from the string "0".

Important Behavior and Edge Cases

  • Key behavior: Reads bytes rather than UTF-8 characters. Test strictly against false to distinguish EOF from the string "0".
  • Environment: Requires an open readable stream.

Comparison With Related Functions

FunctionPurpose
fgetc()Reads a single byte from a file stream.
fread()fread() reads a given number of bytes; fgetc() reads one byte.

Common Beginner Mistakes

MistakeCorrect Approach
Ignoring this behavior: Reads bytes rather than UTF-8 charactersReads bytes rather than UTF-8 characters. Test strictly against false to distinguish EOF from the string "0".

Key Takeaways

  • Reads a single byte from a file stream.
  • Reads bytes rather than UTF-8 characters. Test strictly against false to distinguish EOF from the string "0".
  • Requires an open readable stream.

Summary: Reads bytes rather than UTF-8 characters. Test strictly against false to distinguish EOF from the string "0".

Share this resourceSend this page to someone who may find it useful.