2012-12-20 51 views
6

我得到一個30秒的超時錯誤,因爲代碼保持檢查,如果該文件是超過5MB時,它的下面。該代碼旨在拒絕超過5MB的文件,但我需要它也停止執行,當文件低於5MB。有沒有辦法檢查文件傳輸塊是否爲空?我目前使用這個例子的DaveRandom:PHP停止讀取遠程文件時後完全下載

PHP Stop Remote File Download if it Exceeds 5mb

代碼由DaveRandom

$url = 'http://www.spacetelescope.org/static/archives/images/large/heic0601a.jpg'; 
$file = '../temp/test.jpg'; 
$limit = 5 * 1024 * 1024; // 5MB 

if (!$rfp = fopen($url, 'r')) { 
    // error, could not open remote file 
} 
if (!$lfp = fopen($file, 'w')) { 
    // error, could not open local file 
} 

// Check the content-length for exceeding the limit 
foreach ($http_response_header as $header) { 
    if (preg_match('/^\s*content-length\s*:\s*(\d+)\s*$/', $header, $matches)) { 
    if ($matches[1] > $limit) { 
     // error, file too large 
    } 
    } 
} 

$downloaded = 0; 

while ($downloaded < $limit) { 
    $chunk = fread($rfp, 8192); 
    fwrite($lfp, $chunk); 
    $downloaded += strlen($chunk); 
} 

if ($downloaded > $limit) { 
    // error, file too large 
    unlink($file); // delete local data 
} else { 
    // success 
} 
+0

展我們迄今爲止的代碼是您嘗試使用它的方式。 – davidethell

+0

即時消息使用完全相同的代碼在DaveRandom的回答。它的第一個答案:http://stackoverflow.com/questions/13963158/php-stop-remote-file-download-if-it-exceeds-5mb – webdev

+0

我明白這一點,但它是很好的做法在SO包括相關部分代碼在這篇文章中,以便這個問題可以自行理解。 – davidethell

回答

5

你應該檢查是否已經達到了文件的末尾:

while (!feof($rfp) && $downloaded < $limit) { 
    $chunk = fread($rfp, 8192); 
    fwrite($lfp, $chunk); 
    $downloaded += strlen($chunk); 
} 
+0

謝謝jeroen :),我現在會測試它... – webdev

+1

成功!謝謝Jeroen :) – webdev