6

コードがファイルが 5 MB を超えているかどうかをチェックし続けるため、30 秒のタイムアウト エラーが発生します。コードは 5 MB を超えるファイルを拒否するように設計されていますが、ファイルが 5 MB 未満の場合も実行を停止する必要があります。ファイル転送チャンクが空かどうかを確認する方法はありますか? 私は現在、DaveRandom によるこの例を使用しています。

PHPが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
}
4

1 に答える 1

5

ファイルの終わりに達したかどうかを確認する必要があります。

while (!feof($rfp) && $downloaded < $limit) {
  $chunk = fread($rfp, 8192);
  fwrite($lfp, $chunk);
  $downloaded += strlen($chunk);
}
于 2012-12-20T02:55:47.730 に答える