Page 1 of 1

why ob_clean and flush ?

Posted: Sun May 24, 2009 3:26 pm
by aneuryzma
Hello,

I would like to know why do I need to use ob_clean and flush in this example (in which I want to force a download) and what they exactly do.
thanks!

Code: Select all

 
//force a download
 
<?php
$file = 'monkey.gif';
 
if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
}
?>
 

Re: why ob_clean and flush ?

Posted: Sun May 24, 2009 4:39 pm
by requinix
void ob_clean ( void )

This function discards the contents of the output buffer.
void flush ( void )

Flushes the output buffers of PHP and whatever backend PHP is using (CGI, a web server, etc). This effectively tries to push all the output so far to the user's browser.

flush() has no effect on the buffering scheme of your web server or the browser on the client side. Thus you need to call both ob_flush() and flush() to flush the output buffers.

Several servers, especially on Win32, will still buffer the output from your script until it terminates before transmitting the results to the browser.

Server modules for Apache like mod_gzip may do buffering of their own that will cause flush() to not result in data being sent immediately to the client.

Even the browser may buffer its input before displaying it. Netscape, for example, buffers text until it receives an end-of-line or the beginning of a tag, and it won't render tables until the </table> tag of the outermost table is seen.

Some versions of Microsoft Internet Explorer will only start to display the page after they have received 256 bytes of output, so you may need to send extra whitespace before flushing to get those browsers to display the page.
If you have output buffering enabled then ob_clean would get rid of everything that's been printed so far, and flush... wouldn't really accomplish much.