我遇到了一个30秒的超时错误,因为代码一直在检查文件是否超过5mb,而实际上它并没有超过。这段代码被设计用来拒绝超过5mb的文件,但是我需要它在文件小于5mb时停止执行。有没有一种方法可以检查文件传输块是否为空?目前我正在使用DaveRandom的这个示例:
PHP如果远程文件下载超过5mb则停止 PHP Stop Remote File Download if it Exceeds 5mb DaveRandom的代码:
PHP如果远程文件下载超过5mb则停止 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
}