PHP - Check if something was print in the browser
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 Tra开发者_StackOverflow社区nsfer');
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.
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();
}
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.
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.
精彩评论