3

是否可以使用 cURL 获取文件的最后 1MB 数据?我知道我可以获得第一个 MB,但我需要最后一个。

4

2 回答 2

4

是的,您可以通过在请求中指定 HTTP Range 标头来执行此操作:

// $curl = curl_init(...);
$lower = $size - 1024 * 1024;
$upper = $size;
url_setopt($curl, CURLOPT_HTTPHEADER, array("Range: bytes=$lower-$upper"));

注意:您需要确保您请求数据的服务器允许这样做。发出HEAD请求,并检查Accept-Ranges标头。

这是一个示例,您应该可以对其进行调整以满足您的需求:

// Make HEAD request
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_NOBODY, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($curl);

preg_match('/^Content-Length: (\d+)/m', $data, $matches);
$size = (int) $matches[1];
$lower = $size - 1024 * 1024;

// Get last MB of data
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_HTTPGET, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Range: bytes=$lower-$size"));

$data = curl_exec($curl);
于 2012-12-11T16:23:14.387 回答
0

我知道这是一个老问题,但你可以通过只指定上限来做到这一点:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Get the last 100 bytes and echo the results
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Range: bytes=-100"));
echo htmlentities(curl_exec($ch)) . "<br /><br />";

// Get the last 200 bytes and echo the results
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Range: bytes=-200"));
echo htmlentities(curl_exec($ch));

这将返回:

100 bytes: <p><a href="http://www.iana.org/domains/example">More information...</a></p> </div> </body> </html> 

200 bytes: ou may use this domain in examples without prior coordination or asking for permission.</p> <p><a href="http://www.iana.org/domains/example">More information...</a></p> </div> </body> </html>

来自RFC 2616

通过选择 last-byte-pos,客户端可以在不知道实体大小的情况下限制检索的字节数。

于 2017-04-09T13:57:00.010 回答