是否可以使用cURL获取文件的最后1MB数据?我知道我可以获得第一个MB,但我需要最后一个MB。
答案 0 :(得分:4)
是的,您可以通过在请求中指定HTTP范围标题来执行此操作:
// $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);
答案 1 :(得分: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,客户端可以在不知道实体大小的情况下限制检索的字节数。