pankaj roy
pankaj roy

Reputation: 81

Php curl get amount of bytes written

How can i know how much data is written in php curl . Here is my code which downloads i.e writes the data to my local server from a remote url . But i want to know how much data has been written till now .

    <?php
    $url  = 'https://speed.hetzner.de/1GB.bin';
    $path = $_SERVER['DOCUMENT_ROOT'] . '/1gb.bin';

    $fp = fopen($path, 'w');

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_FILE, $fp);

    $data = curl_exec($ch);

    curl_close($ch);
    fclose($fp);

Upvotes: 1

Views: 2046

Answers (1)

Accountant م
Accountant م

Reputation: 7533

I use this for the downloaded size in bytes (including the size of the file as it is the body of the response) (after you call curl_exec($ch);)

 // $ch is the curl handle
 $info = curl_getinfo($ch);
 echo $info['size_download'];

CURLINFO_SIZE_DOWNLOAD - Total number of bytes downloaded

This is quoted from libcurl documenation

The amount is only for the latest transfer and will be reset again for each new transfer. This counts actual payload data, what's also commonly called body. All meta and header data are excluded and will not be counted in this number.

And this for the size of the request you made with curl in bytes

 $info = curl_getinfo($ch);
 echo $info['request_size'];

CURLINFO_REQUEST_SIZE - Total size of issued requests, currently only for HTTP requests

you can also use the function with the opt parameter set to one of the function constants, like

echo curl_getinfo($ch, CURLINFO_REQUEST_SIZE);
echo curl_getinfo($ch, CURLINFO_SIZE_DOWNLOAD);

getinfo() function

As you told in comments by Dharman, don't switch off CURLOPT_SSL_VERIFYPEER. If you want to use https requests check this php-curl-https

Upvotes: 2

Related Questions