Content · Programming · PHP

PHP fstat() Function: Usage and Examples

Understand PHP fstat() with three examples, return behavior, important pitfalls, and related operations.

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

Use fstat() when you need to returns metadata for a file represented by an open stream in a PHP application. The examples below show the actual operation and its limitations.

What Is fstat() in PHP?

Returns metadata for a file represented by an open stream. The exact signature supported by your installation depends on its PHP version and enabled extensions.

Its syntax is:

fstat($stream): array|false

Parameters and return value: The parameter types, optional arguments, references, and return type are shown in the signature above. Optional parameters are marked with an ellipsis in this reference signature.

Example 1: Basic Usage

<?php

$stream = fopen("php://temp","w+"); fwrite($stream,"Hello"); echo fstat($stream)["size"]; fclose($stream);

Output:

5

Example 2: Different Input or Behavior

<?php

$stream = tmpfile(); fwrite($stream,"1234"); echo fstat($stream)["size"]; fclose($stream);

Output:

4

Practical Example: Applying the Function

<?php

$stream = tmpfile(); fwrite($stream,"invoice"); $metadata = fstat($stream); echo $metadata === false ? "Unavailable" : "Bytes: ".$metadata["size"]; fclose($stream);

Output:

Bytes: 7

Important Behavior and Edge Cases

Not all metadata fields are meaningful on every stream wrapper or platform.

Comparison With Related Functions

ApproachDifference
fstat()Returns metadata for a file represented by an open stream.
Related operationstat() works on a pathname; fstat() inspects an already open stream.

Common Beginner Mistakes

MistakeCorrect Approach
Ignoring the function-specific limitationNot all metadata fields are meaningful on every stream wrapper or platform.
Confusing this function with a related operationstat() works on a pathname; fstat() inspects an already open stream.

Key Takeaways

  • Returns metadata for a file represented by an open stream.
  • Not all metadata fields are meaningful on every stream wrapper or platform.
  • stat() works on a pathname; fstat() inspects an already open stream.

Use fstat() for the specific operation demonstrated above. Check its prerequisites and handle failure conditions before using it with production data.

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