Content · Programming · PHP

PHP fputs() Function: Usage and Examples

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

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

Use fputs() when you need to writes bytes to a stream and is an alias of fwrite() in a PHP application. The examples below show the actual operation and its limitations.

What Is fputs() in PHP?

Writes bytes to a stream and is an alias of fwrite(). The exact signature supported by your installation depends on its PHP version and enabled extensions.

Its syntax is:

fputs($stream, string $data, ?int $length = ...): int|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+"); fputs($stream,"Hello"); rewind($stream); echo stream_get_contents($stream); fclose($stream);

Output:

Hello

Example 2: Different Input or Behavior

<?php

$stream = fopen("php://temp","w+"); echo fputs($stream,"ABCDE",3); fclose($stream);

Output:

3

Practical Example: Applying the Function

<?php

$stream = fopen("php://temp","w+"); foreach (["one","two"] as $line) fputs($stream,$line."
"); rewind($stream); echo stream_get_contents($stream); fclose($stream);

Output:

one
two

Important Behavior and Edge Cases

A write can be partial; check the number of bytes written, especially with network streams.

Comparison With Related Functions

ApproachDifference
fputs()Writes bytes to a stream and is an alias of fwrite().
Related operationfwrite() is exactly the same operation; fputs() is its alias.

Common Beginner Mistakes

MistakeCorrect Approach
Ignoring the function-specific limitationA write can be partial; check the number of bytes written, especially with network streams.
Confusing this function with a related operationfwrite() is exactly the same operation; fputs() is its alias.

Key Takeaways

  • Writes bytes to a stream and is an alias of fwrite().
  • A write can be partial; check the number of bytes written, especially with network streams.
  • fwrite() is exactly the same operation; fputs() is its alias.

Use fputs() 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.