PHP完全下载后停止读取远程文件

时间:2012-12-20 02:48:33

标签: php

我收到了30秒的超时错误,因为代码一直在检查文件是否超过5mb。该代码旨在拒绝超过5mb的文件,但我需要它也在文件低于5mb时停止执行。有没有办法检查文件传输块是否为空?我目前正在使用DaveRandom的这个例子:

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
}

1 个答案:

答案 0 :(得分:5)

您应该检查是否已到达文件的末尾:

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