Control result size curl

1

Hello, I have to pull data from a feed using Curl in PHP. Once extracted, I write the result to my bank.

The problem is that the result of the call is giant. Is there any way to control this flow?

This is the code:

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://site.com/?_restfully=true&fromDate=2017-09-07");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");

$headers = array();
$headers[] = "Authorization: Bearer $token";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);

if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}
curl_close ($ch);
    
asked by anonymous 08.09.2017 / 06:44

1 answer

0

PHP, as always , is not supported for CURLOPT_XFERINFOFUNCTION and not even CURLOPT_MAXFILESIZE is listed there ... One way I see, but not necessarily the best, is to use CURLOPT_WRITEFUNCTION , as follows:

$result = '';
$size = 0;
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://site.com/?_restfully=true&fromDate=2017-09-07");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $content) use (&$result, $size){
    $result .= $content;
    $len = strlen($content);
    $size += $len;

    if($size > 1000){
        return 0;
    }

    return $len;
});
curl_exec($ch);

if (curl_getinfo($ch, CURLINFO_HTTP_CODE) !== 200) {
    die();
}

echo $result;

In this way the result will be limited to 1000 bytes. In fact this limit is not so rigid, CURLOPT_WRITEFUNCTION is not called to each received byte, but to each data block, that is to say there may be 1000 bytes or 500 bytes. For this reason it may be that result is more than 1000 bytes, but when there are more than 1000 bytes it will stop getting the rest.

    
08.09.2017 / 09:12