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
| Approach | Difference |
|---|---|
fputs() | Writes bytes to a stream and is an alias of fwrite(). |
| Related operation | fwrite() is exactly the same operation; fputs() is its alias. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Ignoring the function-specific limitation | A write can be partial; check the number of bytes written, especially with network streams. |
| Confusing this function with a related operation | fwrite() 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.