3

I need to limit the size of the file to be downloaded and tried using CURLOPT_PROGRESSFUNCTION option with a callback to check on the size of the download and stop when it goes beyond 1kb this way:

$progress_handler = function( $download_size, $downloaded, $upload_size, $uploaded ) {
    return ( $downloaded > 1024 ) ? 1 : 0;
}

curl_setopt($ch, CURLOPT_NOPROGRESS, false);
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, $progress_handler);

I tested this on few sites with download size in ~100kb but doesn't seem to stop at 1kb. Are there any other ways to apply the limit?

Thanks!

zanderwar
  • 3,440
  • 3
  • 28
  • 46
user2727704
  • 625
  • 1
  • 10
  • 21
  • duplicate? [How to partially download a remote file with cURL?](http://stackoverflow.com/questions/2032924/how-to-partially-download-a-remote-file-with-curl) – Ryan Vincent Jun 29 '16 at 01:30

1 Answers1

0

This works:

<?php

$url = 'https://example.com/file';

$ch = curl_init($url);

$bytes = 0;

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_NOHEADER, 1);
curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $data) use(&$bytes) {
    static $size = 0;

    //echo $data;

    $size += strlen($data);

    $bytes = $size;

    if ($size > 1024) {
        return -1;
    }
    return strlen($data);
});

$res = curl_exec($ch);

echo "Got $bytes bytes\n";

The concept is to use CURLOPT_WRITEFUNCTION to receive the data from the response body and increment a static counter local to the function. Once the number of bytes exceeds 1024, return -1 to abort the transfer. A value is shared between the callback and the program so you can check the value of $bytes after the transfer to see if it was greater than your target size or not.

drew010
  • 68,777
  • 11
  • 134
  • 162
  • Actually using CURLOPT_PROGRESSFUNCTION works too, I had a typo which was previously causing it to fail. Thanks! – user2727704 Jun 29 '16 at 06:35