views:

37

answers:

3

How can I check if something was print in the browser? I've tried headers_sent but it's for headers... If nothing was printed i want to download a file:

public function download() {
    $file = null;
    $line = null;

    if(headers_sent($file, $line)) {
        /* generic exception... change that... */
        throw new Exception('Headers was sent before in file ' . $file . ', line #' . $line);
    }

    header('Content-Description: File Transfer');
    header('Content-Type: ' . $this->mime);
    header('Content-Disposition: attachment; filename=' . $this->name);
    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: ' . $this->size);
    readfile($this->path);

Thank you.

A: 

The short answer is you can't. After you have sent data to the client, you have no chance of finding out what gets done with that data.

This question has some workaround ideas, but none of them is anywhere near fail-safe.

Pekka
I think the OP means "Is there a way to find out if something was already output to stdout.", not printing to a physical media.
nikc
@nikc yeah, you're right. I was distracted by the "print"
Pekka
A: 

You can use PHP Output control functions to check if there was any output to the browser.

Example:

<?php

ob_start();

echo 'something';

$output = ob_get_contents();

if (!empty($output))
{
    die('something was printed');
}
else
{
    readfile();
}
donis
A: 

I don't know of any way of detecting if output is already started. I suppose headers_sent is a way to detect that, since PHP will send the headers when it runs into the first output in the executing script.

If you need to control when the output is started, you should probably look into output buffering control.

nikc
no need to know. to read a manual page is enough
Col. Shrapnel
@Col: which manual page would that be? There is no explicit statement about detecting sent output on the `headers_sent` manual page. My explanation of PHP's behaviour should be correct and how the function can be used to derive that information. Where is the value in your comment?
nikc