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

标签 php

我收到 30 秒超时错误,因为代码会不断检查文件是否超过 5mb。该代码旨在拒绝超过 5mb 的文件,但我需要它在文件小于 5mb 时也停止执行。有没有办法检查文件传输 block 是否为空?我目前正在使用 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
}

最佳答案

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

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

关于PHP 在完全下载后停止读取远程文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13964547/

相关文章:

php - 使用 LIKE 语句执行时 PDO 的疯狂行为

php 内的链接的 javascript 不起作用

PHP 和 SQL INSERT JOIN 2 个表,条件错误

php - 如何在PHP中自动优化mysql数据库?

PHP Regex 匹配字符串中的单词,不包括一个特定单词

php - 为什么 google chrome 将我的页面放在窗口的正中央(CSS 和 HTML 问题)?

php - 如何添加数据并在sql语句中打印

php - 调用通用静态类方法 php

php - 如何从 mac 终端运行我的 php 文件

php - PDO 的行数