如何使用cURL部分下载远程文件?

Ken*_*Ken 21 php curl

是否可以使用cURL部分下载远程文件?假设,远程文件的实际文件大小为1000 KB.我怎么才能下载前500 KB呢?

Vol*_*erK 35

您还可以使用php-curl扩展名设置范围标头参数.

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.spiegel.de/');
curl_setopt($ch, CURLOPT_RANGE, '0-500');
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
echo $result;
Run Code Online (Sandbox Code Playgroud)

但如前所述,如果服务器不遵守此标头但发送整个文件curl将下载所有文件.例如http://www.php.net忽略标题.但是你可以(另外)设置一个写函数回调并在接收到更多数据时中止请求,例如

// php 5.3+ only
// use function writefn($ch, $chunk) { ... } for earlier versions
$writefn = function($ch, $chunk) { 
  static $data='';
  static $limit = 500; // 500 bytes, it's only a test

  $len = strlen($data) + strlen($chunk);
  if ($len >= $limit ) {
    $data .= substr($chunk, 0, $limit-strlen($data));
    echo strlen($data) , ' ', $data;
    return -1;
  }

  $data .= $chunk;
  return strlen($chunk);
};

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.php.net/');
curl_setopt($ch, CURLOPT_RANGE, '0-500');
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_WRITEFUNCTION, $writefn);
$result = curl_exec($ch);
curl_close($ch);
Run Code Online (Sandbox Code Playgroud)


Spl*_*iFF 17

获取文档的前100个字节:

curl -r 0-99 http://www.get.this
Run Code Online (Sandbox Code Playgroud)

从手册

确保你有一个现代的卷曲

  • 你是对的,但我发现它并不总是可靠的,取决于服务器而不是自己卷曲.在行为不端的情况下,curl会继续下载. (3认同)