Use fpassthru() when you need to writes the remaining bytes of an open stream directly to output in a PHP application. The examples below show the actual operation and its limitations.
What Is fpassthru() in PHP?
Writes the remaining bytes of an open stream directly to output. The exact signature supported by your installation depends on its PHP version and enabled extensions.
Its syntax is:
fpassthru($stream): int
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"); rewind($stream); fpassthru($stream); fclose($stream);
Result: Run the example in an environment that supports the function. Any values depending on operating-system state, installed extensions, process configuration, or network access must be checked on the target server.
Example 2: Different Input or Behavior
<?php
$stream = fopen("php://temp", "w+"); fwrite($stream,"ABCDE"); fseek($stream,2); fpassthru($stream); fclose($stream);
Result: Run the example in an environment that supports the function. Any values depending on operating-system state, installed extensions, process configuration, or network access must be checked on the target server.
Practical Example: Applying the Function
<?php
$stream = fopen("php://temp", "w+"); fwrite($stream,"CSV,data
"); rewind($stream); $bytes = fpassthru($stream); fclose($stream); echo "
Bytes: " . $bytes;
Result: Run the example in an environment that supports the function. Any values depending on operating-system state, installed extensions, process configuration, or network access must be checked on the target server.
Important Behavior and Edge Cases
Data is sent to output rather than returned as a string; the stream pointer matters.
Comparison With Related Functions
| Approach | Difference |
|---|---|
fpassthru() | Writes the remaining bytes of an open stream directly to output. |
| Related operation | stream_get_contents() returns data as a string; fpassthru() sends it to output. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Ignoring the function-specific limitation | Data is sent to output rather than returned as a string; the stream pointer matters. |
| Confusing this function with a related operation | stream_get_contents() returns data as a string; fpassthru() sends it to output. |
Key Takeaways
- Writes the remaining bytes of an open stream directly to output.
- Data is sent to output rather than returned as a string; the stream pointer matters.
- stream_get_contents() returns data as a string; fpassthru() sends it to output.
Use fpassthru() for the specific operation demonstrated above. Check its prerequisites and handle failure conditions before using it with production data.