phpcurl

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


Is there a maximum size limit to PHP cURL downloads? ie. will cURL quit when transfer reaches a certain file limit?

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);

It's for a site that downloads remote images. I want to ensure that cURL will stop when it reaches a certain limit.

Also my research shows getimagesize() downloads the image, to return its size so its not an option.


Solution

  • 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.