2010-10-13 38 views
0

如何檢查瀏覽器中是否打印了某些東西?我試過headers_sent但它的頭...... 如果沒有印我想下載一個文件:PHP - 檢查瀏覽器中是否有東西被打印

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); 

謝謝。

+1

headers_sent是你需要的 – 2010-10-13 14:17:30

+0

你的代碼應該按原樣工作。如果您輸出了任何東西(假設您沒有啓用輸出緩衝),'headers_sent'將返回true,因爲您第一次執行PHP會爲您發送適當的標頭。 – meagar 2010-10-13 14:21:42

+0

headers_sent不起作用:<?php echo'hi'; echo headers_sent(); //沒有輸出,所以它是假的??> – thomas 2010-10-13 15:01:11

回答

0

簡短的答案是你不能。在您將數據發送給客戶端後,您無法找出該數據的完成情況。

This question有一些解決方法的想法,但沒有一個是靠近自動防故障的。

+0

我認爲OP的意思是「有沒有辦法找出是否已經輸出到標準輸出。」,而不是打印到物理介質。 – 2010-10-13 14:17:42

+0

@nikc是的,你是對的。我被「打印」 – 2010-10-13 14:22:05

0

您可以使用PHP Output control functions來檢查是否有任何輸出到瀏覽器。

例子:

<?php 

ob_start(); 

echo 'something'; 

$output = ob_get_contents(); 

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

我不知道,如果輸出已經啓動檢測任何方式。我認爲headers_sent是一種檢測的方法,因爲PHP在運行到執行腳本的第一個輸出時會發送標題。

如果您需要控制何時開始輸出,您應該查看output buffering control

+0

分心了,不需要知道。閱讀手冊頁就足夠了 – 2010-10-13 14:21:58

+0

@Col:哪個手冊頁會是?關於在'headers_sent'手冊頁上檢測發送輸出沒有明確的聲明。我對PHP的行爲的解釋應該是正確的,以及函數如何用於派生信息。評論中的價值在哪裏? – 2010-10-14 06:19:55