Home > PHP > Write To The Output Buffer In PHP

Write To The Output Buffer In PHP

February 10th, 2009 Tech Leave a comment Go to comments

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.

Information, services, and products:
Environmental Consultants required
Categories: PHP Tags: , , , , , ,
  1. Super 7 Lotto
    February 17th, 2009 at 17:33 | #1

    thanks for the code, very useful for me.

  1. No trackbacks yet.