PHP Stop Reading Remote Files when after it is Fully Downloaded
<p>I'm getting a 30 second timeout error because the code keeps checking if the file is over 5mb when it's under. The code is designed to reject files over 5mb but i need it to also stop executing when the file is under 5mb. Is there a way to check the file transfer chunk to see if it's empty? I'm currently using this example by DaveRandom:</p>

<p><a href="http://stackoverflow.com/questions/13963158/php-stop-remote-file-download-if-it-exceeds-5mb">PHP Stop Remote File Download if it Exceeds 5mb</a></p>

<p>Code by <a href="http://stackoverflow.com/users/889949/daverandom">DaveRandom</a>:</p>

<pre><code>$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] &gt; $limit) {
      // error, file too large
    }
  }
}

$downloaded = 0;

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

if ($downloaded &gt; $limit) {
  // error, file too large
  unlink($file); // delete local data
} else {
  // success
}
</code></pre>
