How to set a maximum size limit to PHP cURL downloads?

I have another answer that addresses the situation even better to leave here for posterity.

CURLOPT_WRITEFUNCTION is good for this but CURLOPT_PROGRESSFUNCTION is the best.

// We need progress updates to break the connection mid-way
curl_setopt($cURL_Handle, CURLOPT_BUFFERSIZE, 128); // more progress info
curl_setopt($cURL_Handle, CURLOPT_NOPROGRESS, false);
curl_setopt($cURL_Handle, CURLOPT_PROGRESSFUNCTION, function(
    $DownloadSize, $Downloaded, $UploadSize, $Uploaded
){
    // If $Downloaded exceeds 1KB, returning non-0 breaks the connection!
    return ($Downloaded > (1 * 1024)) ? 1 : 0;
});

Keep in mind that even if the PHP.net states^ for CURLOPT_PROGRESSFUNCTION:

A callback accepting five parameters.

My local tests have featured only four (4) parameters as the 1st (handle) is not present.

Leave a Comment