Write To The Output Buffer In PHP

The first thing you learn about in PHP is probably how to print something. This is usually done with a call to the echo or print, but there is another way to print things by writing content directly to the output buffer. The following code looks like you are writing to a file, but the text will appear in the browser window because we are writing to the php://output output stream.

$fp = fopen("php://output", 'r+');
fputs($fp, "Hello World");

Or another way...

file_put_contents("php://output", "Hello World");

The php://output stream is an encapsulation between PHP and the browser. The stream doesn't really exist, but PHP knows what to do with it.

Why would you ever need to know this? Well lets say that you had an application that produced some logs when users performed certain actions. You might want to print those to screen in your development environment rather than save them. So rather than altering the code to see what environment you are in you can just set a configuration option so that you write to php://output instead of the log file. This means that your logs will appear with your output.

Comments

thanks for the code, very useful for me.
Permalink

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
2 + 1 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.