PHP cURL Download Size Limit

Posted on July 24, 2013 at 4:07 pm

Callback function used the check bytes downloaded in real-time:

function my_custom_download_callback($ch, $chunk) { 
  static $content = ''; //default value is empty
  static $bytes_limit = 10000; // limit to download only 10 KB
 
  $len = strlen($content) + strlen($chunk);
  if ($len >= $bytes_limit ) {
    $content .= substr($chunk, 0, $bytes_limit-strlen($content));
    return $content;
  }
 
  $content .= $chunk;
  return strlen($chunk);
}

Function used to download a file:

function my_custom_download( $url )
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_BUFFERSIZE, 500); //Buffer size (bytes) you want to read on each call
    curl_setopt($ch, CURLOPT_WRITEFUNCTION, 'my_custom_download_callback'); //Callback to our function
    $output = curl_exec($ch);
    $bytes = my_custom_download_callback(null, null);
    curl_close($ch);
    return $bytes;
}

The download function will download only the first 10 KB of the file.

Or use these options to block download of file and return error:

// Limit the download size to N bytes (250K by default)
//https://stackoverflow.com/questions/17641073/how-to-set-a-maximum-size-limit-to-php-curl-downloads
curl_setopt($ch, CURLOPT_BUFFERSIZE, 128);
curl_setopt($ch, CURLOPT_NOPROGRESS, false);
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, function($DownloadSize, $Downloaded, $UploadSize, $Uploaded){ return ($Downloaded > 250000) ? 1 : 0; });

Updated on January 25, 2019 at 1:23 pm

Receive updates via email

Other Posts

Updated Posts